gpt4 book ai didi

java - 如何在 Java 中检测损坏的图像(PNG、JPG)

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:55 25 4
gpt4 key购买 nike

我需要在 Java 中检测图像文件是否损坏。我只处理 PNG、JPG 图像。这可能与 Sanselan 有关吗?或者可以用 ImageIO 来完成吗?我试过使用 ImageIO.read 似乎有效。但我不确定它是否可以检测图像中的各种错误。我想知道什么是最佳做法。

最佳答案

这是我的解决方案,可以处理损坏的 GIF、JPG 和 PNG 的检查。它使用 JPEG EOF 标记检查截断的 JPEG,使用索引越界异常检查检查 GIF,使用 EOFException 检查 PNG

public static ImageAnalysisResult analyzeImage(final Path file)
throws NoSuchAlgorithmException, IOException {
final ImageAnalysisResult result = new ImageAnalysisResult();

final InputStream digestInputStream = Files.newInputStream(file);
try {
final ImageInputStream imageInputStream = ImageIO
.createImageInputStream(digestInputStream);
final Iterator<ImageReader> imageReaders = ImageIO
.getImageReaders(imageInputStream);
if (!imageReaders.hasNext()) {
result.setImage(false);
return result;
}
final ImageReader imageReader = imageReaders.next();
imageReader.setInput(imageInputStream);
final BufferedImage image = imageReader.read(0);
if (image == null) {
return result;
}
image.flush();
if (imageReader.getFormatName().equals("JPEG")) {
imageInputStream.seek(imageInputStream.getStreamPosition() - 2);
final byte[] lastTwoBytes = new byte[2];
imageInputStream.read(lastTwoBytes);
if (lastTwoBytes[0] != (byte)0xff || lastTwoBytes[1] != (byte)0xd9) {
result.setTruncated(true);
} else {
result.setTruncated(false);
}
}
result.setImage(true);
} catch (final IndexOutOfBoundsException e) {
result.setTruncated(true);
} catch (final IIOException e) {
if (e.getCause() instanceof EOFException) {
result.setTruncated(true);
}
} finally {
digestInputStream.close();
}
return result;
}

public class ImageAnalysisResult {
boolean image;
boolean truncated;
public void setImage(boolean image) {
this.image = image;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
}
}

关于java - 如何在 Java 中检测损坏的图像(PNG、JPG),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8039444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com