ruby Carrierwave图像模型验证图像尺寸/高度/宽度。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Carrierwave图像模型验证图像尺寸/高度/宽度。相关的知识,希望对你有一定的参考价值。

# encoding: utf-8

class ImageUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url
    "/uploads/missing/#{model.class.to_s.underscore}/#{version_name}.png"
  end
  
  # for image size validation
  # fetching dimensions in uploader, validating it in model
  attr_reader :width, :height
  before :cache, :capture_size
  def capture_size(file)
    if version_name.blank? # Only do this once, to the original version
      if file.path.nil? # file sometimes is in memory
        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
  
  # resizing uploads
  
  process :resize_to_fill => [148, 148]

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_white_list
    %w(jpg jpeg png)
  end

end
class Banner < ActiveRecord::Base
  attr_accessor :image_width, :image_height
  mount_uploader :image, ImageUploader
  
  validate :check_dimensions, :on => :create
  def check_dimensions
    if !image_cache.nil? && (image.width < 300 || image.height < 300)
      errors.add :image, "Dimension too small."
    end
  end

end

以上是关于ruby Carrierwave图像模型验证图像尺寸/高度/宽度。的主要内容,如果未能解决你的问题,请参考以下文章

ruby 更新s3上的carrierwave图像

Rails Carrierwave和Imagemagick,使用条件调整图像大小

在 ActiveAdmin 中使用 CarrierWave 多个图像

Rails 4使用carrierwave上传多个图像或文件

使用 image_tag 显示通过 CarrierWave 上传的图像

Carrierwave - 处理后的图像尺寸太大