File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes How can i find out how many colors in a BufferedImage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How can i find out how many colors in a BufferedImage" Watch "How can i find out how many colors in a BufferedImage" New topic
Author

How can i find out how many colors in a BufferedImage

ying lam
Ranch Hand

Joined: May 17, 2004
Posts: 85
I try the following code snippet in order to find out how many colors in a BufferedImage, but it always returns 3. But i am sure that image has more than 3 color. Can you please tell me how can i find out how many color in an image?





Thank you.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
But there are only three colours. Red, green blue.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

The getNumComponents() method does not do what you think it does. It returns the number of component colors used for each pixel. Almost all computer and TV screens have three components (red, green, blue) that are "mixed" together to make a color. It does not return information like a histogram, which is what you seem to expect.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
ying lam
Ranch Hand

Joined: May 17, 2004
Posts: 85
Thanks. But is there a way I can find out how many colors (different RGB combination) used in an image using Java?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

Use the getRGB method for every single pixel. Store those in a Map:

This code uses the advantages of both generics and autoboxing. Keep in mind that this could produce a really really big map - there are 256^3 different possibilities for RGB only, and that doesn't even take into account the alpha part.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
Nice bit of code, but it's worth checking whether the getRGB method returns RGB or what Color#getRGB() returns, viz aRGB. Then rather than using RGB straight use . . .getRGB() & 0xffffff. That will reduce the combinations from 2^32 to 2^24. Still >16,000,000 however.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How can i find out how many colors in a BufferedImage