【发布时间】:2011-11-23 13:57:12
【问题描述】:
所有上传的文件至少应为 150x150 像素。如何使用 Carrierwave 进行验证?
【问题讨论】:
标签: ruby-on-rails imagemagick carrierwave
所有上传的文件至少应为 150x150 像素。如何使用 Carrierwave 进行验证?
【问题讨论】:
标签: ruby-on-rails imagemagick carrierwave
为什么不使用 MiniMagick?修改 DelPiero 的答案:
validate :validate_minimum_image_size
def validate_minimum_image_size
image = MiniMagick::Image.open(picture.path)
unless image[:width] > 400 && image[:height] > 400
errors.add :image, "should be 400x400px minimum!"
end
end
【讨论】:
:picture,您将向:picture 属性添加错误,而不是:image
我根据@skalee 的回答做了一个稍微完整的验证器
class ImageSizeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value.blank?
image = MiniMagick::Image.open(value.path)
checks = [
{ :option => :width,
:field => :width,
:function => :'==',
:message =>"Image width must be %d px."},
{ :option => :height,
:field => :height,
:function => :'==',
:message =>"Image height must be %d px."},
{ :option => :max_width,
:field => :width,
:function => :'<=',
:message =>"Image width must be at most %d px."},
{ :option => :max_height,
:field => :height,
:function => :'<=',
:message =>"Image height must be at most %d px."},
{ :option => :min_width,
:field => :width,
:function => :'>=',
:message =>"Image width must be at least %d px."},
{ :option => :min_height,
:field => :height,
:function => :'>=',
:message =>"Image height must be at least %d px."},
]
checks.each do |p|
if options.has_key?(p[:option]) and
!image[p[:field]].send(p[:function], options[p[:option]])
record.errors[attribute] << p[:message] % options[p[:option]]
end
end
end
end
end
像validates :image, :image_size => {:min_width=>400, :min_height => 400}一样使用它。
【讨论】:
让我感到惊讶的是,寻找一种使用 CarrierWave 验证图像宽度和高度的明确方法是多么困难。 @Kir 上面的解决方案是正确的,但我想进一步解释他做了什么,以及我所做的小改动。
如果您查看他的要点https://gist.github.com/1239078,答案就在于他在 Uploader 类中的 before :cache 回调。魔法线是
model.avatar_upload_width, model.avatar_upload_height = `identify -format "%wx %h" #{new_file.path}`.split(/x/).map { |dim| dim.to_i }
在他的例子中, avatar_upload_width 和 avatar_upload_height 是他的 User 模型的属性。我不想有在数据库中存储宽度和高度,所以在我的模型中我说:
attr_accessor :image_width, :image_height
请记住,您可以将 attr_accessor 用于在弄乱记录时想要手头的属性,但只是不想将它们持久化到数据库中。所以我的魔法线居然变成了
model.image_width, model.image_height = `identify -format "%wx %h" #{new_file.path}`.split(/x/).map { |dim| dim.to_i }
所以现在我将图像的宽度和高度存储在模型对象中。最后一步是为维度编写自定义验证,因此在您的模型中您需要类似
validate :validate_minimum_image_size
然后在它下面定义您的自定义验证方法,与 gist 中的相同
# custom validation for image width & height minimum dimensions
def validate_minimum_image_size
if self.image_width < 400 && self.image_height < 400
errors.add :image, "should be 400x400px minimum!"
end
end
【讨论】:
我刚刚制作了一个自定义验证器,旨在使 Rails 4+ 语法更加友好。
我从这个线程上其他人的回复中汲取了想法。
要点如下:https://gist.github.com/lou/2881f1aa183078687f1e
你可以这样使用它:
validates :image, image_size: { width: { min: 1024 }, height: { in: 200..500 } }
在这种特殊情况下应该是:
validates :image, image_size: { width: 150, height: 150 }
【讨论】: