PDA

View Full Version : RGB to HSB color conversion


pixelwit
08-20-2002, 04:33 AM
I've managed to cobble this code together form various sources which converts from RGB to HSB:function rgb2Hex (r,g,b){
return(r<<16 | g<<8 | b);
}
function hsb2rgb(h, s, v) {
var r, g, b;
if (h == 360) {h = 0;}
else if (h>360 or h<0) {return 0;}
s /= 100;
v /= 100;
h /= 60;
var i = Math.floor(h);
var f = h-i;
var p = v*(1-s);
var q = v*(1-(s*f));
var t = v*(1-(s*(1-f)));
if (i==0) {r=v; g=t; b=p;}
else if (i==1) {r=q; g=v; b=p;}
else if (i==2) {r=p; g=v; b=t;}
else if (i==3) {r=p; g=q; b=v;}
else if (i==4) {r=t; g=p; b=v;}
else if (i==5) {r=v; g=p; b=q;}
r = Math.floor(r*255);
g = Math.floor(g*255);
b = Math.floor(b*255);
return (rgb2Hex(r, g, b));
}Now I'd like to be able to go the other way and convert from RGB to HSB. Can anyone lend a hand?

Thanks for your time,

-PiXELWiT
http://www.pixelwit.com

pixelwit
08-20-2002, 07:52 PM
I did some searching on the Net and found this handy link: http://www.efg2.com/Lab/Library/Color/Science.htm

So after doing a little more cobbling and tweaking I finally have everything the way I like it. Here it is if you're interested:function hsv2rgb(hue, sat, val) {
var red, grn, blu, i, f, p, q, t;
hue%=360;
if(val==0) {return({r:0, g:0, v:0});}
sat/=100;
val/=100;
hue/=60;
i = Math.floor(hue);
f = hue-i;
p = val*(1-sat);
q = val*(1-(sat*f));
t = val*(1-(sat*(1-f)));
if (i==0) {red=val; grn=t; blu=p;}
else if (i==1) {red=q; grn=val; blu=p;}
else if (i==2) {red=p; grn=val; blu=t;}
else if (i==3) {red=p; grn=q; blu=val;}
else if (i==4) {red=t; grn=p; blu=val;}
else if (i==5) {red=val; grn=p; blu=q;}
red = Math.floor(red*255);
grn = Math.floor(grn*255);
blu = Math.floor(blu*255);
return ({r:red, g:grn, b:blu});
}
//
function rgb2hsv(red, grn, blu) {
var x, val, f, i, hue, sat, val;
red/=255;
grn/=255;
blu/=255;
x = Math.min(Math.min(red, grn), blu);
val = Math.max(Math.max(red, grn), blu);
if (x==val){
return({h:undefined, s:0, v:val*100});
}
f = (red == x) ? grn-blu : ((grn == x) ? blu-red : red-grn);
i = (red == x) ? 3 : ((grn == x) ? 5 : 1);
hue = Math.floor((i-f/(val-x))*60)%360;
sat = Math.floor(((val-x)/val)*100);
val = Math.floor(val*100);
return({h:hue, s:sat, v:val});
}
//
// Usage
h = 360;
s = 50;
v = 25;
trace("H"+h+" S"+s+" V"+v);
trace ("Converts to");
col = hsv2rgb(h, s, v);
r = col.r;
g = col.g;
b = col.b;
trace("R"+r+" G"+g+" B"+b);
trace("");
trace("R"+r+" G"+g+" B"+b);
trace ("Converts to");
col = rgb2hsv(r, g, b);
h = col.h;
s = col.s;
v = col.v;
trace ("H"+h+" S"+s+" V"+v);Hope it helps,

-PiXELWiT
http://www.pixelwit.com