我可以打开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();
}
}
请告诉我如何解决问题。
答案 0 :(得分:0)
如果在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