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

前端 未结 1 351
傲寒
傲寒 2020-12-24 03:47

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?

相关标签:
1条回答
  • 2020-12-24 04:06

    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!

    0 讨论(0)
提交回复
热议问题