获取图片主要色素
package com.bootdo.common.utils;
import net.coobird.thumbnailator.Thumbnails;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
public class ClothingColorUtils {
public static float colorNum = 51.0f;
public static Map<Integer, String> colorStandard = new HashMap<Integer, String>();
static {
colorStandard.put(0, "00");
colorStandard.put(1, "33");
colorStandard.put(2, "66");
colorStandard.put(3, "99");
colorStandard.put(4, "cc");
colorStandard.put(5, "ff");
}
@SuppressWarnings({ "static-access", "deprecation" })
public static String tenToHex(int x) {
Integer ten = new Integer(x);
String hex = ten.toHexString(ten);
return hex;
}
public static Integer hexToTen(String hex) {
Integer x = Integer.parseInt(hex, 16);
return x;
}
public static String changeRgb(int r, int g, int b) {
int rk = Math.round(Float.parseFloat(r + "") / colorNum);
int gk = Math.round(Float.parseFloat(g + "") / colorNum);
int bk = Math.round(Float.parseFloat(b + "") / colorNum);
String rs = colorStandard.get(rk);
String gs = colorStandard.get(gk);
String bs = colorStandard.get(bk);
return rs + gs + bs;
}
public static int[] changeToRgb(int pixel) {
int[] rgb = new int[3];
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
return rgb;
}
@SuppressWarnings("deprecation")
public static List<String> recognition(String input) {
String path = input.substring(input.indexOf("=") + 1, input.length());
try {
int[] rgb = new int[3];
BufferedImage bi = Thumbnails.of(path).size(100, 100).asBufferedImage();
Map<String, Integer> colorCount = new HashMap<String, Integer>();
for (int w = 0; w < bi.getWidth(); w = w + 2) {
for (int h = 0; h < bi.getHeight(); h = h + 2) {
rgb = changeToRgb(bi.getRGB(w, h));
String hexColor = changeRgb(rgb[0], rgb[1], rgb[2]);
Integer count = colorCount.get(hexColor);
if (count == null) {
count = new Integer(0);
}
count++;
colorCount.put(hexColor, count);
}
}
Map<Integer, String> colorCountRev = new HashMap<Integer, String>();
List<Integer> countList = new ArrayList<Integer>();
for (String key : colorCount.keySet()) {
colorCountRev.put(colorCount.get(key), key);
countList.add(colorCount.get(key));
}
Collections.sort(countList);
int length = countList.size();
if (length > 6) {
length = 6;
}
String colors = "";
List<String> list = new ArrayList<>();
for (int i = 1; i <= length; i++) {
colors = String.valueOf(colorCountRev.get(countList.get(countList.size() - i)));
list.add(colors);
}
return list;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
System.out.println(recognition("D:/logo/SPDB.png"));
}
}