Bug之javax.imageio.IIOException: Error reading PNG metadata

问题描述

在用thumbnailator包的时候遇到一个问题:就是png文件元数据有损坏,但是在电脑上该png文件是可以显示的。
问题代码如下:

 File file = new File("D:\\data\\1.png");
        try {
            Thumbnails.of(file).height(300).asBufferedImage();
        } catch (IOException e) {
            e.printStackTrace();
        }

错误的日志信息如下:

javax.imageio.IIOException: Error reading PNG metadata
    at java.desktop/com.sun.imageio.plugins.png.PNGImageReader.readMetadata(PNGImageReader.java:849)
    at java.desktop/com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1310)
    at java.desktop/com.sun.imageio.plugins.png.PNGImageReader.read(PNGImageReader.java:1679)
    at net.coobird.thumbnailator.tasks.io.FileImageSource.read(Unknown Source)
    at net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask.read(Unknown Source)
    at net.coobird.thumbnailator.Thumbnailator.createThumbnail(Unknown Source)
    at net.coobird.thumbnailator.Thumbnails$Builder.asBufferedImage(Unknown Source)
    at com.zhanghanlun.business.ThreadDemo.main(ThreadDemo.java:21)
Caused by: javax.imageio.IIOException: Invalid chunk length 226139622
    at java.desktop/com.sun.imageio.plugins.png.PNGImageReader.readMetadata(PNGImageReader.java:734)
    ... 7 more

问题解决

关于该问题的解决,是用ImageIO类将png图片转成jpg图片就可以了,具体的代码如下:

File file = new File("D:\\data\\1.png");
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
                    bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
            newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
            ImageIO.write(newBufferedImage, "jpg", new File("D:\\data\\3.jpg"));
            Thumbnails.of(new File("D:\\data\\3.jpg")).height(300).asBufferedImage();
        } catch (IOException e) {
            e.printStackTrace();
        }

提取其中转换方法为新的方法如下:

public void convertPngToJpg(File file,String newFilePath){
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),bufferedImage.getHeight(),BufferedImage.TYPE_INT_RGB);
            newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, null);
            ImageIO.write(newBufferedImage,"jpg",new File(newFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(Bug记录,Java)