Rails - Paperclip - 如何在保存前检查图像尺寸 [英] Rails - Paperclip - How to Check the Image Dimensions before saving

查看:49
本文介绍了Rails - Paperclip - 如何在保存前检查图像尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有回形针的 Rails 3 应用程序.我想防止回形针保存宽度/高度为 LTE 50x50 的图像.

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.

这可能吗?

推荐答案

是的!这是我为我的应用编写的自定义验证,它应该可以在您的应用中逐字运行,只需将像素设置为您想要的任何值即可.

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

需要注意的一点,我使用了 self.width=self.height= 来将尺寸保存到数据库中,如果您愿意,可以将它们排除在外不关心存储图像尺寸.

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.

检查宽度和高度意味着只有一个必须大于 50px.如果你想确保两者都超过 50 你,具有讽刺意味的是,需要检查宽度或高度.对我来说,一个或另一个表示 AND 检查,而两者都表示 OR,这对我来说似乎很奇怪,但在这种情况下确实如此.

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?"

那应该照顾它!

这篇关于Rails - Paperclip - 如何在保存前检查图像尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆