2

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?

Community
  • 1
  • 1
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

2 Answers2

2

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.

Harald K
  • 26,314
  • 7
  • 65
  • 111
0

Took me some time to figure this out and like to share with others. It's Jruby call Java method, but logic is same. Metadata format is defined at here.

iis = ImageIO.createImageInputStream(ByteArrayInputStream.new(document_data.to_java_bytes))
      itrs = ImageIO.getImageReaders(iis)
      if itrs.has_next
        reader = itrs.next
        reader.setInput(iis)
        metadata = reader.getImageMetadata(0)
        if metadata.is_standard_metadata_format_supported
          color_depth = metadata.getAsTree('javax_imageio_1.0')
            .getElementsByTagName('Chroma').item(0)
            .get_elements_by_tag_name('NumChannels').item(0)
            .getAttribute('value')

          pdf_image.setBlackWhite(true) if color_depth == '1'

        end