验证下载的图像

Validating downloaded image

这会将图像下载到磁盘:

image = open permalink_url, "rb", &:read
...
File.binwrite "images/#{hash}", image

有时它会损坏:

虽然没有例外

  1. 如何检查图像是否已正确下载(否则重试该过程)?
  2. 多少是可以的,没有例外?它怎么发生的?网络异常是否在某个中间服务器上被屏蔽了?

UPD:Imagemagick 说 identify "reports if an image is incomplete or corrupt" 但它没有:

$ identify temp.png
temp.png PNG 1080x1080 1080x1080+0+0 8-bit sRGB 2.126MB 0.000u 0:00.049

这里有两张损坏的图片:

  1. https://drive.google.com/file/d/0B3BLwu7Vb2U-MnNqdHV4MzFSX2s/view?usp=sharing
  2. https://drive.google.com/file/d/0B3BLwu7Vb2U-d3Fab2lmT1hvZlE/view?usp=sharing

UPD:我重新下载了图像并做了一些分析——坏的变体在中间某处有 300000 个额外的字节被分解成很多碎片。垃圾不仅是 0x00,而且看起来是随机的。

使用任何图像处理 gem,例如chunky_png:

require 'chunky_png'
begin
  ChunkyPNG::Datastream.from_file('bad.png')
rescue ChunkyPNG::CRCMismatch
  puts "png corrupted!"
end

编辑:在这种情况下,DatastreamImage 更有效。

编辑 2:如果您希望能够验证 ImageMagick 可以处理的任何格式并且不介意调用外部二进制文件,这应该可行:

unless system('identify', '-verbose', 'bad.jpg', out: IO::NULL, err: IO::NULL)
  puts "the file can't be opened or is corrupted"
end