Ruby on Rails: How do you check if a file is an image?

Viewed 14186

How would you check if a file is an image? I'm thinking you could use an method like so:

def image?(file)
  file.to_s.include?(".gif") or file.to_s.include?(".png") or file.to_s.include?(".jpg")
end

But that might be a little inefficient and not correct. Any ideas?

(I'm using the paperclip plugin, btw, but I don't see any methods to determine whether a file is an image in paperclip)

7 Answers

Since you're using Paperclip, you can use the built in "validates_attachment_content_type" method in the model where "has_attached_file" is used, and specify which file types you want to allow.

Here's an example from an application where users upload an avatar for their profile:

has_attached_file :avatar, 
                  :styles => { :thumb => "48x48#" },
                  :default_url => "/images/avatars/missing_avatar.png",
                  :default_style => :thumb

validates_attachment_content_type :avatar, :content_type => ["image/jpeg", "image/pjpeg", "image/png", "image/x-png", "image/gif"]

The documentation is here http://dev.thoughtbot.com/paperclip/classes/Paperclip/ClassMethods.html

i honestly think this is way easier, use mimemagic gem:

first install it

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 this might be more elegant

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

imagemagick has a command called identity that handles this - check w/ the paperclip documentation - there's probably a way to handle this from within your RoR app.

Related