B4J Question Convert RGB to HSB

Sandman

Expert
Licensed User
Longtime User
First of all, as far as I can tell HSB is same as HSL/HSV. (At least according to Wikipedia: https://en.wikipedia.org/wiki/HSB_color_space)

Secondly, I asked my buddy Google and she came up with this javascript code which is almost readable and might be inspiration?

https://gist.github.com/jonathantneal/2121882

Here's the relevant code:
B4X:
function RGBToHSL(r, g, b) {
   var
   min = Math.min(r, g, b),
   max = Math.max(r, g, b),
   diff = max - min,
   h = 0, s = 0, l = (min + max) / 2;

   if (diff != 0) {
       s = l < 0.5 ? diff / (max + min) : diff / (2 - max - min);

       h = (r == max ? (g - b) / diff : g == max ? 2 + (b - r) / diff : 4 + (r - g) / diff) * 60;
   }

   return [h, s, l];
}
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
This might do what you want (uses javaobject library in UI application)
B4X:
…
 Dim hsb(3) As Float = RGBtoHSB(200,170,75) ' r g b values
 Log("(H)ue          : "&hsb(0))
 Log("(S)aturation % : "&hsb(1))
 Log("(B)rightness % : "&hsb(2))
End Sub
Sub RGBtoHSB(red As Int,green As Int,blue As Int) As Float()
 Dim HSB(3) As Float
 Dim p As JavaObject = fx.Colors.RGB(red,green,blue)
 HSB(0)=p.RunMethod("getHue",Null)  ' degree value
 HSB(1)=p.RunMethod("getSaturation",Null)*100  ' to percentile value
 HSB(2)=p.RunMethod("getBrightness",Null)*100  ' to percentile value
 Return HSB
End Sub
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…