Java examples for 2D Graphics:BufferedImage
Gets the top x numbers of color from BufferedImage
//package com.java2s; import java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; public class Main { /**//from w ww. j a v a 2 s . com * Gets the top x numbers * @param numColors - the number of colors to return * @return - An array of colors, indexed in descending order (Most Popular is 0 index). */ public static Color[] getTopColors(int numColors, BufferedImage sourceImage) { Color[] returnColors = new Color[numColors]; HashMap<Color, Integer> colorMap = new HashMap<Color, Integer>(); int width = sourceImage.getWidth(); int height = sourceImage.getHeight(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Color pixelColor = new Color(sourceImage.getRGB(i, j), true); if (pixelColor.getAlpha() != 0) { if (colorMap.containsKey(pixelColor)) { colorMap.put(pixelColor, colorMap.get(pixelColor) + 1); } else { colorMap.put(pixelColor, 1); } } } } for (int c = 0; c < numColors; c++) { Color topColor = null; int max = -1; for (Map.Entry<Color, Integer> entry : colorMap.entrySet()) { if (max < entry.getValue()) { topColor = entry.getKey(); max = entry.getValue(); } } colorMap.remove(topColor); returnColors[c] = topColor; } return returnColors; } }