This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
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 Elasticsearch in Action this week in the Big Data 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: 41096
    
  29
But there are only three colours. Red, green blue.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14600
    
  25

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: 19908
    
  23

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: 41096
    
  29
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.
 
 
subject: How can i find out how many colors in a BufferedImage