简体   繁体   中英

Converting Decimal BGR color to individual RGB decimal values

I have a database table which is storing color values as a BGR (blue, green, red), and for use in full calendar need to have them formated in a RGB(decimal, decimal, decimal) string. Is there a better way then converting to hex, then splitting, then back to decimal?

example BGR color: 13369599

color = ("%06x" % 13369599).to_s.split(/(..)(..)(..)/)

=> ["", "cc", "00", "ff"]

rgb_value = "rgb( " << color[3].hex.to_s << "," << color[2].hex.to_s << "," << color[1].hex.to_s << ");"

desired output

rgb_value = rgb( 255,00,204);

One of my first languages was C, and the following would be a fairly trivial macro.

color = ((color & 0xff0000) >> 16) | (color & 0x00ff00) | ((color & 0x0000ff) << 16)

Put this inside a bgr_to_rgb method and forget about it. There is no need to reach for #to_s or #hex .

To get the individual R, G, B values from a BGR code, use

red = color & 0x0000ff
green = color & 0x00ff00
blue = color & 0xff0000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM