Check if the file is valid.

I am using rmagick to manage image files. First, I use ImageList.new for each file. When I apply this method to an invalid image file, I get the following error, which aborts the script execution:

RMagick.rb: 1635: in `read ': wrong image title (Magick :: ImageMagickError)

So I would like to be able to check if the file is a valid image file before using this method.

Any ideas? Thanks.

+2


a source to share


3 answers


An exception seems like a perfect signal that an image is invalid ... Why not just save it?



If you really want to apply some other tests, you can use FastImage and ask for the type or size, for example, and you will get nil

if the header is damaged.

+3


a source


You can check the aspect ratio. For instance:

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

      

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



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

      

It is not based on the filename extension. This gives you the actual file format.

+2


a source


If you are processing images of a specific format (s), you can analyze their headers to determine if they are indeed valid image files.

For example, the first 3 bytes of the header of a GIF file are "GIF", according to this GIF specification - so if you receive a file with an extension .gif

, you can parse it to make sure its header matches the spec.

0


a source







All Articles