Who likes this?

1 person have marked this snippet as a favorite

AS3 RGB Colours (object) to HSB Colours (Object)

/ Published in: ActionScript 3   1. var darkGreenRgbObj:Object = new Object();
2. darkGreenRgbObj.r = 51;
3. darkGreenRgbObj.g = 102;
4. darkGreenRgbObj.b = 0;
5. var darkGreenHsbObj:Object = RGBtoHSB(darkGreenRgbObj.r, darkGreenRgbObj.g, darkGreenRgbObj.b);
6. trace("RGB: " + darkGreenRgbObj.r + ", " + darkGreenRgbObj.g + ", " + darkGreenRgbObj.b);
7. trace("HSB: " + darkGreenHsbObj.h + ", " + darkGreenHsbObj.s + ", " + darkGreenHsbObj.b);
8.
9. function RGBtoHSB(r:int, g:int, b:int):Object
10. {
11. var hsb:Object = new Object;
12. var _max:Number = Math.max(r,g,b);
13. var _min:Number = Math.min(r,g,b);
14.
15. hsb.s = (_max != 0) ? (_max - _min) / _max * 100: 0;
16. hsb.b = _max / 255 * 100;
17.
18. if(hsb.s == 0){
19. hsb.h = 0;
20. }else{
21. switch(_max)
22. {
23. case r:
24. hsb.h = (g - b)/(_max - _min)*60 + 0;
25. break;
26. case g:
27. hsb.h = (b - r)/(_max - _min)*60 + 120;
28. break;
29. case b:
30. hsb.h = (r - g)/(_max - _min)*60 + 240;
31. break;
32. }
33. }
34.
35. hsb.h = Math.min(360, Math.max(0, Math.round(hsb.h)))
36. hsb.s = Math.min(100, Math.max(0, Math.round(hsb.s)))
37. hsb.b = Math.min(100, Math.max(0, Math.round(hsb.b)))
38.
39. return hsb;
40. }
41.
42. // OUTPUT
43. // RGB: 51, 102, 0
44. // HSB: 90, 100, 40 Subscribe to comments
Posted By: forchid on January 15, 2012

It's a great series of conversions functions that you put up. However in this one, I was experiencing some inconsistency when translating max red into the correlating hue.

I added one line, which seems to have helped to get the proper output for H:

case r: hsb.h = (g - b)/(_max - _min)*60 + 0; if (hsb.h < 0) hsb.h = 360 + hsb.h; // <--- added this break;

Posted By: forchid on January 15, 2012

Bah, that comment formatting didn't seem to work properly, so it looks confusing. This is the line:

if (hsb.h < 0) hsb.h = 360 + hsb.h;