开发者

Check if file is a valid image

I'm usi开发者_Go百科ng rmagick to manipulate image files. I use the ImageList.new on each file to get started. When I apply this method to an invalid image file I get the below error which interrupts the execution of the script:

RMagick.rb:1635:in `read': Improper image header (Magick::ImageMagickError)

Therefore I would like to be able to check whether a file is a valid image file before using this method.

Any ideas? Thanks.


You can check the format of the image. For example:

image = Magick::Image::read(file_path).first
image.format

So you can check if the format is one of the formats you expect:

image = Magick::Image::read(file_path).first
%w(JPEG GIF TIFF PNG).include? image.format

This is not based on the file name extension. It giess you the actual format of the file.


An exception seems like the perfect signal that an image is invalid... Why not simply rescue it?

If you really want to apply some other tests, you could use FastImage and request the type or size, for instance, and you will get nil if the header is corrupted.


If you are processing images of a certain format(s), you could analyze their headers to determine if they are really valid images files.

For example, the first 3 bytes of a GIF file header are "GIF", according to this GIF spec - so if you receive a file with a .gif extension, you could analyze it to verify its header matches the spec.


install mimemagic gem

gem 'mimemagic'

open stream(bytes of target image)

url="https://i.ebayimg.com/images/g/rbIAAOSwojpgyQz1/s-l500.jpg"
result = URI.parse(url).open

then check data-stream's file type

for example:

MimeMagic.by_magic(result).type == "image/jpeg"

even though as mentioned above

%w(JPEG GIF TIFF PNG).include?(MimeMagic.by_magic(result).type)

this might be more elegant

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜