ImageMagick的验证图像的完整性

问题描述 投票:3回答:4

我使用的ImageMagick(带魔杖在Python),将图像转换并从他们那里得到的缩略图。然而,我注意到,我需要验证文件是否是一个图像或不提前。我应该这样做认同?

所以我会承担检查文件的完整性,需要读入内存中的整个文件。是不如尝试和转换的文件,如果有错误,那么我们就知道该文件并不好。

imagemagick imagemagick-convert wand
4个回答
7
投票

好像你回答了你自己的问题

$ ls -l *.png
-rw-r--r-- 1 jsp jsp 526254 Jul 20 12:10 image.png
-rw-r--r-- 1 jsp jsp  10000 Jul 20 12:12 image_with_error.png
$ identify image.png &> /dev/null; echo $?
0
$ identify image_with_error.png &> /dev/null; echo $?
0
$ convert image.png /dev/null &> /dev/null ; echo $?
0
$ convert image_with_error.png /dev/null &> /dev/null ; echo $?
1

1
投票

下面是使用识别另一种解决方案,但没有转换:

identify -verbose *.png 2>&1 | grep "corrupt image"

identify: corrupt image 'image_with_error.png' @ error/png.c/ReadPNGImage/4051.


1
投票

我的情况下,你使用Python,你也可以考虑枕模块。

在我的实验,我都用了,为了检测损坏的图像Pyhton枕头模块(PIL)和ImageMagick的包装棒(用于PSD,XCF格式),原来的答案与代码片段是here

更新:我还实施了在我的Python脚本here on GitHub此解决方案。

我也验证了损坏的文件(JPG)经常不“破”的图像即,损坏的图片文件有时仍是一个合法的图片文件,原始图像丢失或改变,但你仍然可以加载它。结束时更新

我引用的完整性完整的答案:

您可以使用Python枕头(PIL)模块,与大多数图像格式,检查文件是否有效和完整的图像文件。

在您的目标是检测也断图像的情况下,@Nadia Alramli正确地暗示im.verify()方法,但是这不检测所有可能的图像缺陷,例如,im.verify不检测截短的图像(即大多数观众经常与变灰区负载) 。

枕头是能够检测到这些类型的缺陷太多,但你必须申请图像处理或图像解码/重新编码或触发检查。最后,我建议使用此代码:

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

在图像缺陷的情况下,该代码将引发异常。请考虑im.verify比执行图像处理速度约100倍(我认为翻盖更便宜的一次转变)。有了这个代码,你会在大约10兆字节/秒,以验证一组图像(使用现代2.5Ghz的CPU x86_64的单丝)。

对于其他格式PSD,XCF,..你可以使用ImageMagick的包装器棒,代码如下:

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

但是,从我的实验棒不检测截断的图像,我觉得它加载缺少的部分为灰色区域,而不会提示。

我红认为,ImageMagick的具有外部命令识别,可以使这项工作,但我还没有找到一种方法来编程方式调用该函数,我没有测试过这条路线。

我建议总是进行初步检查,检查文件大小不为零(或非常小),是一个非常便宜的想法:

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case

-2
投票

我使用的标识:

$ identify image.tif
00000005.tif TIFF 4741x6981 4741x6981+0+0 8-bit DirectClass 4.471MB 0.000u 0:00.010
$ echo $?
© www.soinside.com 2019 - 2024. All rights reserved.