如何以编程方式检查图像(PNG、JPEG或GIF)是否已损坏?

2024-05-16 23:41:51 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧。所以我有大约250000张高分辨率图像。我想做的是通过所有这些,找到那些被腐蚀的。如果你知道4scrape是什么,那么你就知道图像的本质

对我来说,图片被加载到Firefox,上面写着

The image “such and such image” cannot be displayed, because it contains errors.

现在,我可以选择我所有的250000张图片(~150gb)并将它们拖放到Firefox中。不过,这会很糟糕,因为我不认为Mozilla设计的Firefox可以打开250000个标签。不,我需要一种方法以编程方式检查图像是否损坏。

有没有人知道一个PHP或Python库可以按照这些思路做些什么?或者现有的Windows软件?

我已经删除了明显损坏的图像(例如0字节的图像),但我有99.9%的把握,在我的收藏群中有更多的病态图像。


Tags: andthe图像image图片itbefirefox
3条回答

我建议你去imagemagick看看这个:http://www.imagemagick.org/

这里有一个名为identify的工具,您可以将它与脚本/标准输出结合使用,也可以使用提供的编程接口

一个简单的方法是尝试使用PIL(Python Imaging Library)加载和验证文件。

from PIL import Image

v_image = Image.open(file)
v_image.verify()

捕捉异常。。。

来自the documentation

im.verify()

尝试确定文件是否已损坏,而不实际解码图像数据。如果此方法发现任何问题,则会引发适当的异常。此方法仅适用于新打开的图像;如果图像已加载,则结果未定义。此外,如果使用此方法后需要加载图像,则必须重新打开图像文件。

在PHP中,使用exif_imagetype()

if (exif_imagetype($filename) === false)
{
    unlink($filename); // image is corrupted
}

编辑:或者您可以尝试使用ImageCreateFromString()完全加载图像:

if (ImageCreateFromString(file_get_contents($filename)) === false)
{
    unlink($filename); // image is corrupted
}

An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognized format, or the image is corrupt and cannot be loaded.

相关问题 更多 >