java - 如何在使用 ImageIO.read() 时解决“java.io.EOFException:ZLIB 输入流的意外结束”
问题描述
我可以打开 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();
}
}
请告诉我如何解决问题。
解决方案
如果您在 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
推荐阅读
- scala - 使用带有内部特征的 Scalacheck
- r - 在 R 中,使用矩阵列表,如何快速找到列表中每个矩阵的第一行和第二行之间的差异?
- javascript - JS 全局变量不起作用
- vba - 运行时错误“9”:下标超出范围 VBA Excel 2003
- python - 如何根据以列表为值的列过滤 Pandas 数据框中的行?
- c++ - 如何在使用模板时将cpp代码编译成库文件
- android - Dagger2:编译错误:没有@Inject 构造函数或@Provides-annotated 方法无法提供
- python - 将 txt 文件的行与输出连接到另一个 txt 文件。Python
- php - 从 php 插入到 sql 给出 SQLSTATE[HY093] 错误
- javascript - 如果在 React 15 中嵌套 2 的最佳方法是什么?