package com.what21.swing.image.demo01;
public class RGB {
int red;
int green;
int blue;
public RGB(){ }
public RGB(int red, int green, int blue) {
this.red = red;
this.blue = blue;
this.green = green;
}
public String toString() {
return "RGB {" + red + ", " + green + ", " + blue + "}";
}
}
package com.what21.swing.image.demo01;
import java.util.regex.Pattern;
public class Converter {
/**
* RGB颜色 转 HEX颜色
*
* @param red
* @param green
* @param blue
* @return
*/
public static String toHEX(int red, int green, int blue) {
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0
|| blue > 255) {
return "";
}
String redStr = Integer.toHexString(red);
String greenStr = Integer.toHexString(green);
String blueStr = Integer.toHexString(blue);
return ("#" + redStr + greenStr + blueStr).toUpperCase();
}
/**
* RGB颜色 转 HEX颜色
*
* @param rgb
* @return
*/
public static String toHEX(RGB rgb){
return toHEX(rgb.red,rgb.green,rgb.blue);
}
/**
* HEX颜色 转 RGB颜色
*
* @param hex
* @return
*/
public static RGB toRGB(String hex){
RGB rgb = new RGB();
if(!Pattern.matches("^#[0-9a-f[A-F]]{6}", hex)){
return rgb;
}
String redStr = hex.substring(1,3);
String greenStr = hex.substring(3,5);
String blueStr = hex.substring(5);
rgb.red = Integer.valueOf(redStr,16).intValue();
rgb.green = Integer.valueOf(greenStr,16).intValue();
rgb.blue = Integer.valueOf(blueStr,16).intValue();
return rgb;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(toHEX(222,221,222));
System.out.println(toRGB("#DEDDDE"));
}
}