在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