views:

252

answers:

3

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  A: 

I would use the filemagic module which is a Ruby binding for libmagic.

Sinan Ünür
Thank you Sinan for the great link! I didn't know that existed. Thank you.
sjsc
The file command is really great for this, so this wrapper should do the job.
tadman
+1  A: 

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.

BandsOnABudget
Thanks for the tip Claude and John on the identity. I'll have a check. Thank you so much for the referral.
sjsc
+4  A: 

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

Beerlington
Thank you Beerlington!
sjsc