Question

I'm using something along the lines of this to do a (naive, apparently) check for the color space of JPEG images:

import java.io.*;
import java.awt.color.*;
import java.awt.image.*;
import javax.imageio.*;

class Test
{
    public static void main(String[] args) throws java.lang.Exception
    {
        File f = new File(args[0]);

        if (f.exists())
        {
            BufferedImage bi = ImageIO.read(f);
            ColorSpace cs = bi.getColorModel().getColorSpace();

            boolean isGrayscale = cs.getType() == ColorSpace.TYPE_GRAY;
            System.out.println(isGrayscale);
        }
    }
}

Unfortunately this reports false for images that (visually) appear gray-only.

What check would do the right thing?

Was it helpful?

Solution

You can use this code:

File input = new File("inputImage.jpg");

BufferedImage image = ImageIO.read(input); 

Raster ras = image.getRaster();

int elem = ras.getNumDataElements();

System.out.println("Number of Elems: " + elem);

If the number of elems returns 1, then its a greyscale image. If it returns 3, then its a color image.

OTHER TIPS

the image looks like gray beacuse the r=g=b but actually it is a full color image, it has three channel r g b and the real gray image only have one channel

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top