Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How can i find out how many colors in a BufferedImage

 
ying lam
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49447
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But there are only three colours. Red, green blue.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15369
40
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
ying lam
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20552
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic