RGB与HSB之间的转换公式
先来了解⼀些概念:
1.RGB是⼀种加⾊模型,就是将不同⽐例的Red/Green/Blue混合在⼀起得到新颜⾊.通常RGB颜⾊模型表⽰为:
2.HSB(HSV) 通过⾊相/饱和度/亮度三要素来表达颜⾊.
H(Hue):表⽰颜⾊的类型(例如红⾊,绿⾊或者黄⾊).取值范围为0—360.其中每⼀个值代表⼀种颜⾊.
S(Saturation):颜⾊的饱和度.从0到1.有时候也称为纯度.(0表⽰灰度图,1表⽰纯的颜⾊)
B(Brightness or Value):颜⾊的明亮程度.从0到1.(0表⽰⿊⾊,1表⽰特定饱和度的颜⾊)
后⾯地址是⼀个在线的观察RGB到HSB转换的⼯具:
⽤RGB来表⽰颜⾊虽然⽅便,但是两个相近的颜⾊的RGB值却可能相差⼗万⼋千⾥。⽤HSV(Hue⾊相、Saturation饱和度、Value(Brightness)明度,也叫HSB)来表⽰颜⾊就⽐较符合⼈们的习惯。
RGB到HSV(HSB)的转换:
HSV(HSB)到RGB的转换:
根据以上说明,有以下转换公式(Java代码):
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 Floatpare(h, 0.0f) >= 0 && Floatpare(h, 360.0f) <= 0;
assert Floatpare(s, 0.0f) >= 0 && Floatpare(s, 1.0f) <= 0;
assert Floatpare(v, 0.0f) >= 0 && Floatpare(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;
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;
16进制转换器计算器b = q;
break;
default:
break;
}
return new int[] { (int) (r * 255.0), (int) (g * 255.0), (int) (b * 255.0) };
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论