Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres 9.4: fast way to convert color from hex to rgb representation

I have hex representation color, for sample #112233 stored in Postgresql 9.4

Need convert this representation to rgb(17,34,51) in pl/pgsql function

Any Ideas to convert it fastest way?

like image 641
Dmitry Avatar asked Oct 22 '25 06:10

Dmitry


1 Answers

This uses Erwin's trick to convert a hex value to an integer value:

with colors (hex_code) as (
  values ('#112233'), ('#203040')
)
select 'rgb('||
       ('x'||substr(hex_code,2,2))::bit(8)::int||','||
       ('x'||substr(hex_code,4,2))::bit(8)::int||','||
       ('x'||substr(hex_code,6,2))::bit(8)::int||')'
from colors
;

Not sure if that is the fastest way, but I can't think of a different one. The select expression can be moved into a function without problems.

SQLFiddle demo: http://sqlfiddle.com/#!15/d41d8/3720


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!