1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| public static void RGBToHSL(double r, double g, double b, double[] hsl) {
if(hsl.length!=3)
throw new IllegalArgumentException("HSL.lenght!=3");
double red = (r)/255.0;
double green = ( g)/255.0;
double blue = (b)/255.0;
double max = MillieUtils.max(blue, red, green);
double min = MillieUtils.min(blue, red, green);
//compute H
double h = 0;
if(max==min)
h=0;
else if(max==red)
h = ((int) (60.0 * (green-blue)/(max-min))) % 360;
else if(max==green)
h = ((int)((60.0 * (blue-red)/(max-min) + 120))) % 360;
else if(max==blue)
h = ((int)((60.0 * (red-green)/(max-min) + 240)))% 360;
hsl[0] = h;
//compute S
double s =0;
if(max==min)
s=0;
else if(max+min<=1.0)
s = (max-min)/(max+min);
else s = (max-min)/(2.0-(max+min));
hsl[1] = s;
//compute L
double l = 0.5*(max+min);
hsl[2]=l;
}
public static void RGBToHSL(int rgb, double[] hsl) {
RGBToHSL((rgb >> 16) & 0xFF,(rgb >> 8) & 0xFF,rgb & 0xFF, hsl);
}
public static int HSLToRGB(double[] hsl) {
double q;
double h = hsl[0];
double s = hsl[1];
double l = hsl[2];
int r;
int g;
int b;
if(s==0) {
r = g = b = (int) (255.0*l);
}
else {
if(l<0.5)
q = l * (1+s);
else
q = l+s-(l*s);
double p = 2*l-q;
double hk = h/360.0;
double dR = hue2rgb(p, q, hk+1.0/3.0);
double dG = hue2rgb(p, q, hk);
double dB = hue2rgb(p, q, hk -1.0/3.0);
r = (int) (dR*255.0);
g = (int) (dG*255.0);
b = (int) (dB*255.0);
}
int rgb = (r<<16) + (g<<8) + b;
return rgb;
}
private static double hue2rgb(double p, double q, double tc) {
if(tc<0) tc+=1;
if(tc>1) tc-=1;
if(tc<1.0/6.0)
return p+((q-p)*6.0*tc);
if(tc<1.0/2.0)
return q;
if(tc<2.0/3.0)
return p+((q-p)*6*(2.0/3.0-tc));
return p;
} |
Partager