awt
RGB to HSB and vice versa color conversion
With this example we are going to see how to convert RGB to HSB and vice versa. This is very useful when you want to unify the units in Java Desktop application, and thus make the components much more manageable.
In short, in order to convert RGB to HSB and vice versa, one should follow these steps:
- Create three basic color values in RGB.
- Use
Color.RGBtoHSB(red, green, blue, null)
to convert RGB values to HSB. - Use
Color.HSBtoRGB(hue, saturation, brightness)
to convert HSB to RGB values. - To get the red value do
(rgb>>16)&0xFF.
- To get the green value do
(rgb>>8)&0xFF.
- To get the blue value do
rgb&0xFF.
Let’s see the code:
package com.javacodegeeks.snippets.desktop; import java.awt.Color; public class RGBToHSB { public static void main(String[] args) { // The 3 basic color values in RGB int red = 51; int green = 102; int blue = 153; // Convert RGB to HSB float[] hsb = Color.RGBtoHSB(red, green, blue, null); float hue = hsb[0]; float saturation = hsb[1]; float brightness = hsb[2]; System.out.println("RGB [" + red + "," + green + "," + blue + "] converted to HSB [" + hue + "," + saturation + "," + brightness + "]" ); // Convert HSB to RGB value int rgb = Color.HSBtoRGB(hue, saturation, brightness); red = (rgb>>16)&0xFF; green = (rgb>>8)&0xFF; blue = rgb&0xFF; System.out.println("HSB [" + hue + "," + saturation + "," + brightness + "] converted to RGB [" + red + "," + green + "," + blue + "]" ); } }
Example Output:
RGB [51,102,153] converted to HSB [0.5833333,0.6666667,0.6]
HSB [0.5833333,0.6666667,0.6] converted to RGB [51,102,153]
This was an example on how to convert RGB to HSB and vice versa.