user2897210
user2897210

Reputation: 3

Image operation in java

I'm trying to determine if an image is a black and white image, or if it has color (using Java). If it has color, I need to display a warning message to the user that the color will be lost.

Any suggestion for me?

Upvotes: 0

Views: 287

Answers (2)

Tim Boudreau
Tim Boudreau

Reputation: 1791

ImageIO will allow you to load the image, as someone else mentioned.

An optimization is possible which will help in a lot of cases: If the image is grayscale to begin with - as in, the file format says "this is a grayscale image", you can detect that using img.getColorModel().getColorSpace() to determine if you have an image whose color space only includes shades of gray.

For indexed color palettes (GIF files, for instance), you can iterate all of the colors in the color model and quickly determine if any have color (if the red/green/blue values are identical, there is no color).

For the rest, you'll have to sample pixels from the image (use some pattern to walk the image that skips around between positions so you don't spend a lot of time on black/white/gray borders before encountering color) and do something like

Color c = new Color(img.getRGB(x,y));
boolean isGray = c.getRed() == c.getGreen() && c.getRed() == c.getBlue();
...

At some size of image, it may become too expensive to iterate every pixel of the image to detect if even a single colored pixel exists, and you may want to assume there is some color and warn the user always.

Upvotes: 1

Dark Knight
Dark Knight

Reputation: 8357

It is possible. You can load images with ImageIO.

BufferedImage img = ImageIO.read(imageFile);
int rgb = img.getRGB(x,y);
Color color = new Color(rgb);

But still you need to create an algorithm that finds x,y bounds and check color of each location.

Upvotes: 1

Related Questions