简体   繁体   English

Rails - Paperclip - 如何在保存之前检查图像尺寸

[英]Rails - Paperclip - How to Check the Image Dimensions before saving

I have a Rails 3 app with paperclip. 我有一个带回形针的Rails 3应用程序。 I want to prevent images with a width/height of LTE 50x50 from being saved by paperclip. 我想通过回形针保存宽度/高度为LTE 50x50的图像。

Is this possible? 这可能吗?

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. 有一点需要注意,我使用self.width=self.height=为了将维度保存到数据库,如果您不关心存储图像尺寸,可以将它们保留。

Checking width AND height means that only one has to be greater than 50px. 检查宽度和高度意味着只有一个必须大于50px。 If you want to make sure BOTH are more than 50 you, ironically, need to check width OR height. 如果你想确保BOTH超过50,具有讽刺意味的是,需要检查宽度或高度。 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. 对我来说,似乎很奇怪,一个或另一个意味着AND检查,两者都意味着OR,但在这种情况下,这是真的。

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! 那应该照顾它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM