Count Number of Unique Colors in Image using Java

BufferedImage.getRGB method

package app;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        String imgPath = "test.jpg";

        BufferedImage img = ImageIO.read(new File(imgPath));
        Set<Integer> uniqueColors = new HashSet<>();

        int w = img.getWidth();
        int h = img.getHeight();
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                int pixel = img.getRGB(x, y);
                uniqueColors.add(pixel);
            }
        }

        int totalUniqueColors = uniqueColors.size();

        System.out.println(totalUniqueColors);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.