ImageMagick:用identify检查图片是否完整?(jpg/gif/png图片是否损坏)

一,常用图片格式的结束标志是什么?

1,Jpg格式的文件在16进制中的表示是以 ff d9 两个字节结尾

2,  gif格式的文件,结尾是 3b

3,  png格式的文件,结尾是  00 00 00 00 49 45 4E 44 AE 42 60 82

说明:我们要用到identify的命令,需要安装ImageMagick

参见这一篇:

https://www.cnblogs.com/architectforest/p/12807514.html

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,为什么要查看图片的结束标志?

图片文件在上传过程中受网络情况影响,有可能发生网络中断,

或者处理程序在处理图片时不确定文件是否已上付完成,

图片文件的结束位或结束标志就成为我们检查文件是否完整的标准

三,用linux命令查看图片的结束标志?

1,用xxd命令看一个完整图片的结束标志:

[root@blog html]# xxd a.jpg | tail -2
000041a0: 94ec a491 cc58 b396 354d 8b06 c9b7 6e90  .....X..5M....n.
000041b0: 6922 6997 2294 21f2 bcff d9              i"i.".!....

说明:文件结尾是 ffd9,说明图片文件完整

a.jpg如图:

2,用xxd命令看一个不完整图片的结束标志:

[root@blog html]# xxd b.jpg | tail -2
00002d20: 40a3 ff00 5c67 74f1 5f95 b4df d51e 6b21  @...gt._.....k!
00002d30: 35e3                                     5.

说明:文件结尾不是 ffd9,说明图片文件不完整而是已损坏

b.jpg如图:

3,也可以使用od这个命令,还是上面的两张图片,举例如下:

#--endian=big: 指定大端小端以大端方式输出 

#-h: 指定以16进制输出 

完整图片

[root@blog html]# od --endian=big -h a.jpg | tail -2
0040660 6922 6997 2294 21f2 bcff d900
0040673

损坏图片

[root@blog html]# od --endian=big -h b.jpg | tail -2
0026460 35e3
0026462

四,用identify检查图片是否完整?

1,检查gif是否有损坏?

有损坏的gif

 [root@blog img]$ identify -verbose dog.gif | grep corrupt
identify: corrupt image `dog.gif' @ error/gif.c/DecodeImage/513.
identify: corrupt image `dog.gif' @ error/gif.c/ReadGIFImage/1389.

图片如下:

无损坏的gif

[root@blog img]$ identify -verbose dog_tmb.gif | grep corrupt

没有任何输出 

图片如下:

 

2,检查jpg图片是否有损坏?

有损坏的jpg

[root@blog html]$ identify -verbose b.jpg | grep Corrupt
identify: Premature end of JPEG file `b.jpg' @ warning/jpeg.c/JPEGWarningHandler/390.
identify: Corrupt JPEG data: premature end of data segment `b.jpg' @ warning/jpeg.c/JPEGWarningHandler/390.

无损坏的jpg不会输出包含Corrupt字样的信息

五,查看ImageMaigck的版本:

[root@blog html]# identify --version
Version: ImageMagick 6.9.10-86 Q16 x86_64 2020-01-13 https://imagemagick.org
Copyright: © 1999-2020 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC Modules OpenMP(4.5)
Delegates (built-in): bzlib cairo fftw fontconfig freetype gslib gvc jbig jng jp2 jpeg lcms ltdl 
lzma openexr pangocairo png ps raqm raw rsvg tiff webp wmf x xml zlib
原文地址:https://www.cnblogs.com/architectforest/p/12939272.html