Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file is a valid image

Tags:

ruby

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.

like image 838
some guy Avatar asked Sep 04 '25 03:09

some guy


1 Answers

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.

like image 171
Zack Xu Avatar answered Sep 06 '25 09:09

Zack Xu