tags:

views:

73

answers:

2

Hi all,

I'm using 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.

A: 

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.

Justin Ethier
Yeah that works. I'm using this one-liner to check for PNG images:File.new(filepath,"r").gets[0,4].include?("‰PNG")If someone knows about a library I could use let me know.THanks.
some guy
+1  A: 

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.

Marc-André Lafortune