top.lingyuzhao.utils.ColorUtils Maven / Gradle / Ivy
The newest version!
package top.lingyuzhao.utils;
/**
* @author zhao
*/
public class ColorUtils {
public static float[] rgbToHsl(int r, int g, int b) {
float[] hsl = new float[3];
float rNorm = r / 255.0f;
float gNorm = g / 255.0f;
float bNorm = b / 255.0f;
float max = Math.max(rNorm, Math.max(gNorm, bNorm));
float min = Math.min(rNorm, Math.min(gNorm, bNorm));
float delta = max - min;
hsl[2] = (max + min) / 2.0f;
if (delta == 0) {
hsl[0] = 0;
hsl[1] = 0;
} else {
if (hsl[2] < 0.5f) {
hsl[1] = delta / (max + min);
} else {
hsl[1] = delta / (2.0f - max - min);
}
if (rNorm == max) {
hsl[0] = (gNorm - bNorm) / delta;
} else if (gNorm == max) {
hsl[0] = 2 + (bNorm - rNorm) / delta;
} else {
hsl[0] = 4 + (rNorm - gNorm) / delta;
}
hsl[0] *= 60.0f;
if (hsl[0] < 0) {
hsl[0] += 360.0f;
}
}
return hsl;
}
public static int[] hslToRgb(float h, float s, float l) {
if (s == 0) {
int gray = (int) (l * 255);
return new int[]{gray, gray, gray};
}
float q = l < 0.5 ? l * (1 + s) : l + s - l * s;
float p = 2 * l - q;
float rNorm = hueToRgb(p, q, h + 120);
float gNorm = hueToRgb(p, q, h);
float bNorm = hueToRgb(p, q, h - 120);
return new int[]{
(int) (rNorm * 255),
(int) (gNorm * 255),
(int) (bNorm * 255)
};
}
private static float hueToRgb(float p, float q, float t) {
if (t < 0) t += 360;
if (t > 360) t -= 360;
if (t < 60) return p + (q - p) * t / 60;
if (t < 180) return q;
if (t < 240) return p + (q - p) * (240 - t) / 60;
return p;
}
}