parse Colors From Picture - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Color

Description

parse Colors From Picture

Demo Code


//package com.java2s;

import java.awt.image.BufferedImage;

import java.util.HashMap;

public class Main {
    public static HashMap<Integer, Integer> parseColorsFromPicture(
            BufferedImage img) {/*from  w ww .j  ava  2  s .  co m*/
        HashMap<Integer, Integer> colors = new HashMap<>();
        int w = img.getWidth();
        int h = img.getHeight();

        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                int color = img.getRGB(j, i);
                if (!colors.containsKey(color)) {
                    colors.put(color, 1);
                } else {
                    int pixelsNum = colors.get(color);
                    colors.put(color, pixelsNum + 1);
                }
            }
        }

        return colors;
    }
}

Related Tutorials