Strange PNG errors: Bad length for IHDR chunk

后端 未结 1 2024
借酒劲吻你
借酒劲吻你 2020-12-10 21:47

Heres the error:

Exception in thread \"main\" javax.imageio.IIOException: I/O error reading PNG header!
    at com.sun.imageio.plugins.png.PNGImageReader.rea         


        
相关标签:
1条回答
  • 2020-12-10 22:23

    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.

    0 讨论(0)
提交回复
热议问题