繁体   English   中英

在使用ImageIO.read()时如何弃用'java.io.EOFException:ZLIB输入流的意外结束'

[英]How to soleve 'java.io.EOFException: Unexpected end of ZLIB input stream' while use ImageIO.read()

png

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

我通过使用相同的代码成功读取了其他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();
    }
}

请告诉我如何解决问题。

如果您在Chrome或其他工具中打开图片,将会看到图片的下部(QR码的一部分)丢失了,或者只是黑色。 这是因为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM