Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Paperclip - How to Check the Image Dimensions before saving

I have a Rails 3 app with paperclip. I want to prevent images with a width/height of LTE 50x50 from being saved by paperclip.

Is this possible?

like image 995
AnApprentice Avatar asked Mar 28 '11 04:03

AnApprentice


1 Answers

Yep! Here's a custom validation I wrote for my app, it should work verbatim in yours, just set the pixels to whatever you want.

def file_dimensions
  dimensions = Paperclip::Geometry.from_file(file.queued_for_write[:original].path)
  self.width = dimensions.width
  self.height = dimensions.height
  if dimensions.width < 50 && dimensions.height < 50
    errors.add(:file,'Width or height must be at least 50px')
  end
end

One thing to note, I used self.width= and self.height= in order to save the dimensions to the database, you can leave those out if you don't care to store the image dimensions.

Checking width AND height means that only one has to be greater than 50px. If you want to make sure BOTH are more than 50 you, ironically, need to check width OR height. It seems weird to me that one or the other means an AND check, and both means OR, but in this case that's true.

The only other gotcha is, you need to run this validation LAST: if there are already other errors on the model it will raise an exception. To be honest it's been a while so I don't remember what the error messages were, but in your validation macro use this:

validate :file_dimensions, :unless => "errors.any?"

That should take care of it!

like image 187
Andrew Avatar answered Oct 18 '22 13:10

Andrew