Search code examples
javaimagejavax.imageiocolor-depth

How to get image's (in a file) number of channels (color depth)?


Here we have a good example on how to get image's dimensions from file: https://stackoverflow.com/a/12164026/258483

The method uses ImageReader which tries not to read entire image if it is not required.

Is there a similar method to obtain image's color depth, which is 3 for colored image and 1 for b/w image?

I found it is probably ImageReader#getRawImageType(int) method. Is this correct way?


Solution

  • Yes,

    You can use imageReader.getRawImageType(imageNo). This method will work most of the time. Unfortunately, it will in some cases return null, most notably for JPEG images encoded as YCbCr (instead of RGB), and this is probably the most common case for JPEG...

    Another way to get the same information, is to use the image meta data object, and look at the standard metadata format, to get this information:

    IIOMetadata metadata = imageReader.getImageMetadata(imageNo);
    if (metadata.isStandardFormatSupported()) { // true for all bundled formats
        IIOMetadataNode root = (IIOMetadataNode) imageMetadata.getAsTree("javax_imageio_1.0");
    
        // Get either (as pseudo-xpath):
        // /Chroma/NumChannels[@value], which is just number of channels, 3 for RGB
        // /Data/BitsPerSample[@value], bits per sample, typically 8,8,8 for 24 bit RGB
    }
    

    You can look at the standard format documentation and IIOMetadataNode API doc for more information.