【发布时间】:2013-07-19 09:21:29
【问题描述】:
我正在使用 ImageMagick(在 Python 中使用 Wand)来转换图像并从中获取缩略图。但是,我注意到我需要提前验证文件是否是图像。我应该使用识别来执行此操作吗?
所以我假设检查文件的完整性需要将整个文件读入内存。最好尝试转换文件,如果出现错误,那么我们知道文件不好。
【问题讨论】:
标签: imagemagick imagemagick-convert wand
我正在使用 ImageMagick(在 Python 中使用 Wand)来转换图像并从中获取缩略图。但是,我注意到我需要提前验证文件是否是图像。我应该使用识别来执行此操作吗?
所以我假设检查文件的完整性需要将整个文件读入内存。最好尝试转换文件,如果出现错误,那么我们知道文件不好。
【问题讨论】:
标签: imagemagick imagemagick-convert wand
好像你回答了自己的问题
$ 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
【讨论】:
identify -verbose *.png 2>&1 | grep "corrupt image"identify: corrupt image 'image_with_error.png' @ error/png.c/ReadPNGImage/4051.
identify -verbose *.png 2>&1 | grep "error" 会更好。我有很多文件在识别的输出中没有任何“损坏的图像”文本
identify -verbose image.png 如果有任何错误,实际上会以1 代码退出。不需要grep。然后您可以检查标准错误。问题是,如果您不包含 -verbose 标志,它会以 0 退出。
如果您使用 imagemagick identify 工具指定 regard-warnings 标志
magick identify -regard-warnings myimage.jpg
如果文件有任何警告,它将引发错误。这对于检查图像很有用,而且似乎比使用详细信息要快得多。
【讨论】:
如果你使用 Python,你也可以考虑 Pillow 模块。
在我的实验中,我使用了 Pyhton Pillow 模块 (PIL) 和 Imagemagick 包装器 Wand(用于 psd、xcf 格式)来检测损坏的图像,代码 sn-ps 的原始答案是 here。
更新: 我还在我的 Python 脚本 here on GitHub 中实现了这个解决方案。
我还验证了损坏的文件 (jpg) 通常不是“损坏”的图像,即损坏的图片文件有时仍然是合法的图片文件,原始图像丢失或更改但您仍然可以加载它。 结束更新
为了完整性,我引用了完整的答案:
您可以使用 Python Pillow(PIL) 模块和大多数图像格式来检查文件是否是有效且完整的图像文件。
如果您还打算检测损坏的图像,@Nadia Alramli 会正确建议 im.verify() 方法,但这不会检测到所有可能的图像缺陷,例如,im.verify 不会检测截断的图像(大多数查看器通常加载灰色区域)。
Pillow 也能够检测到这些类型的缺陷,但您必须应用图像处理或图像解码/重新编码或触发检查。最后我建议使用这段代码:
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 MBytes/秒的速度验证一组图像(使用现代 2.5Ghz x86_64 CPU 的单线程)。
对于其他格式psd,xcf,..可以使用Imagemagick包装器Wand,代码如下:
im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()
但是,根据我的实验,Wand 没有检测到截断的图像,我认为它会在没有提示的情况下将缺少的部分加载为灰色区域。
我认为 Imagemagick 有一个外部命令 identify 可以 完成这项工作,但我还没有找到调用该函数的方法以编程方式,我还没有测试过这条路线。
我建议始终进行初步检查,检查文件大小不为零(或非常小),这是一个非常便宜的想法:
statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
#manage here the 'faulty image' case
【讨论】:
这是另一个使用识别但没有转换的解决方案:
identify -verbose *.png 2>&1 | grep "corrupt image"
identify: corrupt image 'image_with_error.png' @ error/png.c/ReadPNGImage/4051.
【讨论】:
我使用识别:
$ identify image.tif
00000005.tif TIFF 4741x6981 4741x6981+0+0 8-bit DirectClass 4.471MB 0.000u 0:00.010
$ echo $?
【讨论】: