let's start by understanding some concepts:1.RGB is an additive color model that mixes different proportions of red/green/blue together to get a new color. The RGB color model is typically represented as:
2.HSB (HSV) expresses color through three elements of hue/saturation/brightness.
H (Hue): Indicates the type of color (for example, red, green, or yellow). The value range is 0-360. Each of these values represents a color.
S (saturation): saturation of the color. from 0 to 1. Sometimes also known as purity. (0 for grayscale, 1 for pure color)
B (brightness or Value): the degree of brightness of the color. from 0 to 1. (0 for Black, 1 for a specific saturation color)
The back address is an online tool for observing RGB to HSB conversions: http://web.bentley.edu/empl/c/ncarter/MA307/color-converter.html
It is convenient to use RGB to represent colors, but the RGB values of the two similar colors may be 108,000 of a difference. Using HSV (hue hue, saturation saturation, Value (brightness) lightness, or HSB) to represent colors is more in line with people's habits.
Conversion of RGB to HSV (HSB):
The conversion of the HSV (HSB) to RGB:
According to the above instructions, there are the following conversion formulas (Java code):
[Java] view Plaincopy
- public static float[] RGB2HSB (int rgbr, int rgbg, int rgbb) {
- Assert 0 <= rgbr && rgbr <= 255;
- Assert 0 <= rgbg && rgbg <= 255;
- Assert 0 <= rgbb && rgbb <= 255;
- int[] RGB = new int[] {rgbr, RGBG, RGBB};
- Arrays.sort (RGB);
- int max = rgb[2];
- int min = rgb[0];
- float HSBB = max/255.0f;
- float Hsbs = max = = 0? 0: (max-min)/(float) max;
- float HSBH = 0;
- if (max = = Rgbr && rgbg >= rgbb) {
- HSBH = (RGBG-RGBB) * 60f/(Max-min) + 0;
- } else if (max = = Rgbr && RGBG < RGBB) {
- HSBH = (RGBG-RGBB) * 60f/(max-min) + 360;
- } else if (max = = RGBG) {
- HSBH = (RGBB-RGBR) * 60f/(max-min) + 120;
- } else if (max = = RGBB) {
- HSBH = (RGBR-RGBG) * 60f/(max-min) + 240;
- }
- return new float[] {HSBH, Hsbs, HSBB};
- }
- public static int[] Hsb2rgb (float h, float s, float v) {
- Assert Float.compare (H, 0.0f) >= 0 && Float.compare (H, 360.0f) <= 0;
- Assert Float.compare (S, 0.0f) >= 0 && Float.compare (S, 1.0f) <= 0;
- Assert Float.compare (V, 0.0f) >= 0 && float.compare (V, 1.0f) <= 0;
- float r = 0, g = 0, b = 0;
- int i = (int) ((H/60)% 6);
- float f = (h/60)-I;
- float p = v * (1-s);
- float q = v * (1-F * s);
- float T = v * (1-(1-f) * s);
- switch (i) {
- Case 0:
- R = V;
- g = t;
- b = P;
- Break
- Case 1:
- R = q;
- g = V;
- b = P;
- Break
- Case 2:
- r = P;
- g = V;
- b = t;
- Break
- Case 3:
- r = P;
- g = q;
- b = V;
- Break
- Case 4:
- R = t;
- g = P;
- b = V;
- Break
- Case 5:
- R = V;
- g = P;
- b = q;
- Break
- Default
- Break
- }
- return new int[] {(int) (R * 255.0), (int) (g * 255.0),
- (int) (b * 255.0)};
- }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Conversion formula between RGB and HSB