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.
a source to share
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.
a source to share
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.
a source to share