1

How to get the color of the image icon.png using java

Actually I have a servlet for that i wll be sending image using multipart file transfer, now the server should respond back the color of the icon file, Here the image file has a single color;

2
  • What do you mean by "single color" of an image file? Unless it's a one-pixel image, there's multiple colors. Commented May 2, 2013 at 21:30
  • @Vulcan single color means all pixels are of same color. Commented May 2, 2013 at 21:32

2 Answers 2

2

Assuming you have the path to the image file:

Color getImageColor(File imagePath) { BufferedImage image = ImageIO.read(imagePath); int color = image.getRGB(0, 0); for (int r = 0; r < image.getHeight(); r += 1) { for (int c = 0; c < image.getWidth(); c += 1) { if (image.getRGB(c, r) != color) { throw new IllegalArgumentException("Image: " + imagePath + " is not a solid color."); } } } return new Color(color); } 

This code assumes that the image really does only have a single color and pulls the first pixel only.

The loop is there to make sure the entire image is one color. There are many ways to handle that situation, of course.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, but why extract the RGB to reconstruct the color, when you can simply do return new Color(image.getRGB(0, 0))?
@ShamsUdDin One option is to loop over the image and throw an exception if the image is not a solid color. I've added some code to do that check. Other options are to average the colors, or to keep track of the most common colors and pick the most used one.
0

You can loop the BufferedImage (two loops - one from 0 to width, and one from 0 to height), and get the call getRgb(x, y). Then count each different value. You can use a Map for that (key = color, value = number of occurences). Note that this will give you counts of how often each color occurs in the image.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.