Strange PNG errors: Bad length for IHDR chunk

浪子不回头ぞ 提交于 2019-11-28 11:46:41

According to the PNG specifiaction:

4.1.1. IHDR Image header

The IHDR chunk must appear FIRST.

Your example image contains a custom critical chunk CgBI as the first chunk, and does not conform to this spec. This is why you get the exception.

Actually, it seems your image is an "iOS optimized PNG".

From http://fileformats.archiveteam.org/wiki/CgBI:

It is not compatible with PNG. Standard PNG decoders that don't support it will fail gracefully, due to an unknown "critical chunk".

Now, what probably should be considered a bug in the com.sun.imageio.plugins.png.PNGImageReader is that it doesn't check that the first chunk is actually a IHDRchunk, before claiming it can read the input.

You can fix the images, by reading them in one of the viewers/apps you say can read them fine, then writing them back as normal PNGs. I tested using Preview on OS X, and it worked fine. Give it a try.

If on OS X (with dev tools), you should also be able to use Apple's modified pngcrush with the following command line:

xcrun -sdk iphoneos pngcrush -revert-iphone-optimizations infile.png outfile.png

If you just want to get the width/height of the images, you don't need to read full BufferedImages, just get an ImageReader and use its getWidth(0) and getHeight(0) methods (there are plenty examples on SO for this already, no need to repeat).

You could probably also create a quick PNG structure parser, that skips the CgBI chunk, and parses the IHDR directly, to get width/height.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!