Color Converter (HEX, RGB, HSL)
import java.awt.Color;
public class ColorConverter {
public static void main(String[] args) {
// HEX to RGB
String hex = "#FF0000";
Color rgb = Color.decode(hex);
int red = rgb.getRed();
int green = rgb.getGreen();
int blue = rgb.getBlue();
System.out.println("RGB value of " + hex + " is (" + red + "," + green + "," + blue + ")");
// RGB to HEX
int r = 255;
int g = 255;
int b = 0;
Color color = new Color(r, g, b);
String hexValue = "#" + Integer.toHexString(color.getRGB()).substring(2).toUpperCase();
System.out.println("HEX value of (" + r + "," + g + "," + b + ") is " + hexValue);
// RGB to HSL
float[] hsl = rgbToHsl(r, g, b);
System.out.println("HSL value of (" + r + "," + g + "," + b + ") is (" + hsl[0] + "," + hsl[1] + "," + hsl[2] + ")");
// HSL to RGB
int[] rgbArray = hslToRgb(hsl[0], hsl[1], hsl[2]);
System.out.println("RGB value of (" + hsl[0] + "," + hsl[1] + "," + hsl[2] + ") is (" + rgbArray[0] + "," + rgbArray[1] + "," + rgbArray[2] + ")");
}
public static float[] rgbToHsl(int r, int g, int b) {
float[] hsl = new float[3];
float r1 = r / 255f;
float g1 = g / 255f;
float b1 = b / 255f;
float max = Math.max(Math.max(r1, g1), b1);
float min = Math.min(Math.min(r1, g1), b1);
float delta = max - min;
float h = 0, s = 0, l = (max + min) / 2;
if (delta != 0) {
if (l < 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
if (r1 == max) {
h = (g1 - b1) / delta;
} else if (g1 == max) {
h = 2 + (b1 - r1) / delta;
} else if (b1 == max) {
h = 4 + (r1 - g1) / delta;
}
h *= 60;
if (h < 0) {
h += 360;
}
}
hsl[0] = h;
hsl[1] = s;
hsl[2] = l;
return hsl;
}
public static int[] hslToRgb(float h, float s, float l) {
int[] rgbArray = new int[3];
float c = (1 - Math.abs(2 * l - 1)) * s;
float x = c * (1 - Math.abs((h / 60) % 2 - 1));
Comments
Post a Comment