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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button