Sg2.9
Converting HSB color values t...
Recent RSS
Converting HSB color values to RGB
From:  Keegan Green
Date:  13. December 2007, 05:12

Hello,

My question is: how can you convert hue, saturation and brightness values to rgb?

I am working on a script to randomly color objects, using a range of colors between 2 user defined colors.

I think that using hsb values for assigning the random colors will work better, but when it comes to assigning colors to objects in scriptographer, the values have to be either cmyk or rgb.

Anyway, does anyone know the math for converting one to the other? I looked it up on wikipidea, but it's all greek to me (I have no math background past high school).

Thanks for any help, I'll post the script once it's working,

Keegan

Re: Converting HSB color values to RGB
Date:  13. December 2007, 12:46

This is some code I picked up from Mootools (I think)..
it works like:
rgbToHsb([r,g,b]);

function rgbToHsb(rgb){
	var red = rgb[0], green = rgb[1], blue = rgb[2];
	var hue, saturation, brightness;
	var max = Math.max(red, green, blue), min = Math.min(red, green, blue);
	var delta = max - min;
	brightness = max / 255;
	saturation = (max != 0) ? delta / max : 0;
	if (saturation == 0){
		hue = 0;
	} else {
		var rr = (max - red) / delta;
		var gr = (max - green) / delta;
		var br = (max - blue) / delta;
		if (red == max) hue = br - gr;
		else if (green == max) hue = 2 + rr - br;
		else hue = 4 + gr - rr;
		hue /= 6;
		if (hue < 0) hue++;
	}
	return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
}

function hsbToRgb(hsb){
	var br = Math.round(hsb[2] / 100 * 255);
	if (hsb[1] == 0){
		return [br, br, br];
	} else {
		var hue = hsb[0] % 360;
		var f = hue % 60;
		var p = Math.round((hsb[2] * (100 - hsb[1])) / 10000 * 255);
		var q = Math.round((hsb[2] * (6000 - hsb[1] * f)) / 600000 * 255);
		var t = Math.round((hsb[2] * (6000 - hsb[1] * (60 - f))) / 600000 * 255);
		switch (Math.floor(hue / 60)){
			case 0: return [br, t, p];
			case 1: return [q, br, p];
			case 2: return [p, br, t];
			case 3: return [p, q, br];
			case 4: return [t, p, br];
			case 5: return [br, p, q];
		}
	}
}
Re: Converting HSB color values to RGB
From:  Keegan Green
Date:  14. December 2007, 01:28

Thanks all!

what a quick and helpful response. I've got it working, so I'll go post the finished script now!

Keegan

Scripts
08.08.14, 15:24
15.05.14, 14:23
02.03.14, 19:16
18.11.13, 14:48
22.03.13, 03:05
22.02.13, 15:45
Posts
10.01.17, 16:37
19.02.16, 06:03
19.02.16, 06:00
17.01.16, 11:00
12.01.16, 13:10
25.11.15, 08:19
Script of the Moment
Cross Hatch Raster 15.03.12