Friday, August 24, 2012

Converting from a hex-string color to its rgbvalue

There are several ways to specify color when one plots using gnuplot.Among them hex-string (like "#0000ff") and rgbvalue (like "256") specification is very important. In this post we will talk about converting from a hex-string color to its rgbvalue (the inversion will be talked in another post).

reset
#pick the red color hex string out
red(colorstring)= colorstring[2:3]
#pick the green color hex string out
green(colorstring)=colorstring[4:5]
#pick the blue color hex string out
blue(colorstring)=colorstring[6:7]
#convert a hex string to its dec format
hex2dec(hex)=gprintf("%0.f",int('0X'.hex))
#calculate the rgb value from the r,g,b weight
rgb(r,g,b) = 65536*int(r)+256*int(g)+int(b)
#convert the hex color string to its rgb value.
hex2rgbvalue(color)=rgb(\
                        hex2dec(red(color)),\
                        hex2dec(green(color)),\
                        hex2dec(blue(color))\
                        ) 
set term png
set output "hex_string2rgbvalue.png"
plot 'color.dat' u 1:2:(hex2rgbvalue(stringcolumn(3)))\
              w lp pt 7 ps 3 lc rgb variable notitle
set output

File 'color.dat' has content like the following:
0 1 #ff0000
1 2 #00ff00
2 3 #0000ff
3 4 #ff00ff
4 5 #ffff00
5 6 #00ffff
0 6 #00ffff
1 5 #ffff00
2 4 #ff00ff
3 3 #0000ff
4 2 #00ff00
5 1 #ff0000

The output file 'hex_string2rgbvalue.png' looks like this:
Fig.1 Converting from a hex-string color to its rgb-value
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.