Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


how to find the number of unique colors in an image using java

loka_karthigaloka_karthiga Member Posts: 2
Explain me how to find get an image and store it in an picture box and too explain me how to create an picture box using java... Please send this to my mail id [color=Green][size=4][email protected][/size][/color]. since i dont know how to find the explain answer in this id......


  • Josh CodeJosh Code Member Posts: 675
    Following here is some code for counting the number of unique colours in an image. It is an application that loads an image from a file and prints out how many unique colours it has.

    Displaying it in a "picture box" is something not covered by the code. If you want to display it in a graphical user interface, you'll have to look into the paint method and the Graphics class.

    The countUniqueColours method creates a BufferedImage with a specific pixel format, TYPE_INT_ARGB. This format involves each pixel being represented by a separate int value.

    A HashSet is used to collect all the unique colours. A HashSet is appropriate and efficient for the job because it averages O(1) access time for the contains method and for adding. Using an array or linked list wouldn't have nearly the speed for checking if another pixel has a unique colour.

    import java.awt.*; // Image
    import java.awt.image.*; // BufferedImage

    import*; // File and IOException
    import javax.imageio.*; // ImageIO

    import java.util.*;

    public class ImageLoader

    public static BufferedImage loadImageFrom(File f) throws IOException

    public static int countUniqueColours(BufferedImage img)
    BufferedImage buf = new BufferedImage(img.getWidth(),img.getHeight(),BufferedImage.TYPE_INT_ARGB);
    int pixels[] = ((DataBufferInt)(buf).getRaster().getDataBuffer()).getData();
    Set coloursFound = new HashSet();
    int width = buf.getWidth();


    for (int y=0;y for (int x=0;x {
    int index = y*width+x;
    int c = pixels[index];

    if (!coloursFound.contains(new Integer(c)))
    coloursFound.add(new Integer(c));

    return coloursFound.size();

    public static void main(String a[])
    if (a.length<1)<br /> {
    System.out.println("Give the name of an image to load.");


    BufferedImage img = loadImageFrom(new File(a[0]));

    // do anything you want with the image.

    System.out.println("The image contains: "+countUniqueColours(img)+" unique pixel colours.");

    catch (IOException ioe)
    System.out.println("Check that '"+a[0]
    +"' exists and is a valid image file.");
Sign In or Register to comment.