首页 > 解决方案 > 如何在使用 ImageIO.read() 时解决“java.io.EOFException:ZLIB 输入流的意外结束”

问题描述

的PNG

我可以打开 png,但使用代码读取它失败。例外是“java.io.EOFException:ZLIB 输入流的意外结束”,第 4 行使用 ImageIO.read() 函数。

我使用相同的代码成功地阅读了其他 png。

public static void cut(String srcImageFile, String result, int x, int y, int width, int height) {
    try {
        // 读取源图像
        BufferedImage bi = ImageIO.read(new File(srcImageFile));
        int srcWidth = bi.getHeight(); // 源图宽度
        int srcHeight = bi.getWidth(); // 源图高度
        if (srcWidth > 0 && srcHeight > 0) {
            Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
            // 四个参数分别为图像起点坐标和宽高
            // 即: CropImageFilter(int x,int y,int width,int height)
            ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
            Image img = Toolkit.getDefaultToolkit()
                    .createImage(new FilteredImageSource(image.getSource(), cropFilter));
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
            g.dispose();
            // 输出为文件
            ImageIO.write(tag, "PNG", new File(result));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

请告诉我如何解决问题。

标签: javajavax.imageioeofexception

解决方案


如果您在 Chrome 或其他工具中打开图像,您会看到图像的下半部分(二维码的一部分)丢失,或者只是黑色。这是因为 PNG 文件确实已损坏,或者似乎被截断了。除了获取文件的新副本,没有截断之外,没有办法“解决”这个问题。

但是,可以使用Java部分读取 PNG 文件,就像在其他工具中一样。它只是不能ImageIO.read(...)使用方便的方法来完成,因为你会得到一个异常并且没有返回值。

相反,使用完整的详细代码:

BufferedImage image;

try (ImageInputStream input = ImageIO.createImageInputStream(file)) {
    ImageReader reader = ImageIO.getImageReaders(input).next(); // TODO: Handle no reader case

    try {
        reader.setInput(input);

        int width = reader.getWidth(0);
        int height = reader.getHeight(0);

        // Allocate an image to be used as destination
        ImageTypeSpecifier imageType = reader.getImageTypes(0).next();
        image = imageType.createBufferedImage(width, height);

        ImageReadParam param = reader.getDefaultReadParam();
        param.setDestination(image);

        try {
            reader.read(0, param); // Read as much as possible into image
        }
        catch (IOException e) {
            e.printStackTrace(); // TODO: Handle
        }
    }
    finally {
        reader.dispose();
    }
}

// image should now contain the parts of the image that could be read

推荐阅读