Wednesday, October 31, 2012

Convertting a rgb color value to its hex-string

In a previous post, I have talked about how to convert a hex-string color to its rgbvalue. This time I will talk about the inversion, i.e., converting a rgb value color specification to its hex-string correspondence.

#pick the red color value out
red(rgbvalue)=rgbvalue/65536
#pick the green color value out
green(rgbvalue)=(rgbvalue%65536)/256
#pick the blue color value out
blue(rgbvalue)=rgbvalue%256
#convert dec color value to its hex string
dec2hex(dec)=gprintf("%02x",dec)
#convert rgb color value to its hex string
rgb2hex(color)="#".\
               dec2hex(red(color)).\
               dec2hex(green(color)).\
               dec2hex(blue(color))

color = 65535 #rgb-value 
print "The hex string of rgb-color ". color ." is: "
print rgb2hex(color)
plot cos(x) w line linecolor rgb rgb2hex(color)

Run this script, it will output the following string and picture.

The hex string of rgb color 65535 is: 
#00ffff

Fig.1 Converting from a rgb color specification to its hex-string


Creative Commons License
Except as otherwise noted, the content of this page is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.