Posts Tagged paperclip
How to validate image dimension in paperclip ?
Posted by eve in ruby on rails on April 2, 2011
I use paperclip gem, v2.3 from https://github.com/thoughtbot/paperclip/tree/master. The problem that I found on using this gem is how to validate image dimension. It seems that plugin doesn’t have method to validate image dimension. Is there an easy way to validate image dimension in paperclip?
There are two gem alternatives to achieve the objective. First alternative, using gem from https://github.com/eugenebolshakov/paperclip, you will find method for validating image dimension. Just put this code on the model :
validates_attachment_dimensions :image, :minimum =>; 300, :maximum => 900
However, I haven’t tested whether it works or not. I prefer with the second gem, which I got from https://github.com/thoughtbot/paperclip/tree/master.
These are the steps of how you setup your project to use that gem to validate your uploaded image dimension :
1) Create module in the config/initializers to get width and height of an image:
module Paperclip class Attachment def width(style = "origina"l) Paperclip::Geometry.from_file(queued_for_write[style]).width unless queued_for_write[style].blank? rescue nil end def height(style = "original") Paperclip::Geometry.from_file(queued_for_write[style]).height unless queued_for_write[style].blank? rescue nil end end end
2) Define custom validate method on the model:
validate :check_image_dimension
def check_image_dimension width = self.try(:avatar).try(:width) height = self.try(:avatar).try(:height) if (width.to_i < 140 || height.to_i < 140) self.errors.add(:avatar, "The selected file could not be uploaded. The image is too small, the minimum dimensions are 140x140 pixels.") end end
Done. 🙂