首先说明如下:
[color=red]给定RGB,确定颜色名称,只能是大概范围,也就是说该RGB最接近的名称,因为在你的列表中不可能列举出所有RGB对应的颜色名称。[/color]
我的思路:
[color=red]遍历你保存的颜色,然后分别和给定的RGB(R,G,B)做比较,然后求平均数,平均数最小的就是最接近的颜色。[/color]
需要两个类:
[code="java"]/**
- 实体类
-
- @author zhq
-
/
public class ColorBean {
/* 颜色的英文名称 /
private String colorEnName;
/* 颜色的中文名称 /
private String colorChName;
/* 颜色的Hex /
private String colorHex;
/* R /
private int r;
/* G /
private int g;
/* B */
private int b;
public ColorBean(int r, int g, int b, String colorName, String colorHex) {
this.r = r;
this.g = g;
this.b = b;
this.colorChName = colorName;
this.colorHex = colorHex;
}
public String getColorEnName() {
return colorEnName;
}
public void setColorEnName(String colorEnName) {
this.colorEnName = colorEnName;
}
public String getColorChName() {
return colorChName;
}
public void setColorChName(String colorChName) {
this.colorChName = colorChName;
}
public String getColorHex() {
return colorHex;
}
public void setColorHex(String colorHex) {
this.colorHex = colorHex;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public int getG() {
return g;
}
public void setG(int g) {
this.g = g;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public String toString() {
return colorChName + "(" + r + " ," + g + " ," + b + ")";
}
}[/code]
[color=red]
测试类:[/color]
[code="java"]import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
- 测试类
-
- @author zhq
-
*/
public class ColorDemo {
private static Random rand = new Random(47);
private static String[] hexNum = { "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F" };
public static List getColorList() {
List<ColorBean> result = new ArrayList<ColorBean>();
for (int i = 0; i < 10; i++) {
StringBuilder sb = new StringBuilder();
for (int k = 0; k < 6; k++)
sb.append(hexNum[rand.nextInt(16)]);
result.add(new ColorBean(rand.nextInt(255), rand.nextInt(255), rand
.nextInt(255), "颜色" + i, "#" + sb.toString()));
}
return result;
}
public static String getColorName(int r, int g, int b) {
String colorName = "";
int minRGB = 765;
ColorBean minColorBean = null;
System.out.println("==========颜色列表========");
for (ColorBean cb : getColorList()) {
System.err.println(cb);
int tempR = Math.abs(r - cb.getR());
int tempG = Math.abs(g - cb.getG());
int tempB = Math.abs(b - cb.getB());
int tempRGB = (tempR + tempG + tempB) / 3;
if (tempRGB <= minRGB) {
minRGB = tempRGB;
minColorBean = cb;
}
colorName = minColorBean.getColorChName();
}
return colorName;
}
public static void main(String[] args) {
String hexStr = getColorName(28, 203, 31);
System.out.println("\nRGB(28, 203, 31)最接近颜色名称是:" + hexStr);
}
}[/code]
[color=red]运行结果:[/color]
==========颜色列表========
颜色0(253 ,35 ,192)
颜色1(28 ,28 ,1)
颜色2(134 ,183 ,26)
颜色3(96 ,112 ,201)
颜色4(198 ,112 ,111)
颜色5(208 ,64 ,20)
颜色6(87 ,209 ,207)
颜色7(54 ,57 ,215)
颜色8(43 ,233 ,41)
颜色9(228 ,218 ,48)
RGB(28, 233, 41)最接近颜色名称是:颜色8
[color=red]注:因为我没有你的数据,所以颜色数据是模拟的。你用的时候,只需要换为你的颜色即可。[/color]