在gemfile中,添加
gem "mini_magick", "~> 3.6.0"
在image_uploader.rb中,添加
include CarrierWave::MiniMagick
...
attr_reader :width, :height
before :cache, :capture_size
def capture_size(file)
if version_name.blank?
if file.path.nil?
img = ::MiniMagick::Image::read(file.file)
@width = img[:width]
@height = img[:height]
else
@width, @height = `identify -format "%wx %h" #{file.path}`.split(/x/).map{|dim| dim.to_i }
end
end
end
在要需要判断的model中
validate :check_dimensions, :on => :create
def check_dimensions
if !image_cache.nil? && (image.width != 1000 || image.height != 1000)
errors.add :image, "图片尺寸必须为 1000*1000"
end
end
在view中
%strong{style: "color:red"}=@sample.errors.messages[:image][0]
more: http://stackoverflow.com/questions/7527887/validate-image-size-in-carrierwave-uploader

本文介绍如何使用 Ruby gem 'mini_magick' 和 CarrierWave 库进行图片尺寸验证。通过在 Gemfile 中添加依赖并配置 uploader 类,可以读取上传文件的尺寸,并在 Model 中实现尺寸校验逻辑。
178

被折叠的 条评论
为什么被折叠?



