幾年前,Randall Monroe(的XKCD)做了large online survey of English-speakers,導致list of over 900 colour names。您可以輕鬆使用這些數據作爲顏色命名函數的基礎,該函數將RGB三元組轉換爲最接近顏色的名稱。這是一個簡單的實施將看起來像在C,例如:
#include <stdio.h>
#define squared(X) ((X) * (X))
typedef struct {
char *name;
unsigned char r, g, b;
} color_name;
/* Source: http://xkcd.com/color/rgb.txt */
/* License: http://creativecommons.org/publicdomain/zero/1.0/ */
static const color_name xkcd_colors[] = {
{"cloudy blue",0xac,0xc2,0xd9}, {"dark pastel green",0x56,0xae,0x57},
{"dust",0xb2,0x99,0x6e}, {"electric lime",0xa8,0xff,0x04},
:
(et cetera)
:
{"blue",0x03,0x43,0xdf}, {"green",0x15,0xb0,0x1a},
{"purple",0x7e,0x1e,0x9c}
};
int main(int argc, char *argv[]) {
int red, green, blue, d2, mind2, i, result;
if (argc != 2 ||sscanf(argv[1],"%02x%02x%02x",&red,&green,&blue) != 3)
return !puts("Provide 6 hex chars as command line argument.");
mind2 = 256 * 256 * 3;
for (i=0; i<sizeof(xkcd_colors)/sizeof(color_name); i++) {
d2 = squared(red - xkcd_colors[i].r) + /* Calculate squared */
squared(green - xkcd_colors[i].g) + /* distance from each */
squared(blue - xkcd_colors[i].b); /* color in list. */
if (d2 < mind2) {
mind2 = d2; /* Find the minimum distance and */
result = i; /* store the index of this color */
}
}
printf("That color is called \"%s\"\n",xkcd_colors[result].name);
return 0;
}
注:你可能要基於不同的數據集,如果你不希望它返回結果的功能像「寶貝狗屎棕色」(#ad900d)或「puke」(#a5a502),但原理是一樣的。
顏色名稱?這在現代有點荒謬,誰有時間查找1670萬個不同的名字? – 2015-03-08 18:47:52
是的,但這是我的項目需求 – user4440416 2015-03-08 18:50:26
......喜歡:http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.birt.doc.isv%2Fmodel%2Fapi%2Forg%2Feclipse%2Fbirt %2Freport%2Fmodel%2Fapi%2Futil%2FColorUtil.html ?? – mico 2015-03-08 18:59:12