3

我有一个 CarrierWave ImageUploader,它创建了几个版本的原始图像,需要根据我的模型中的值(crop_x、crop_y、crop_w 和crop_h)进行裁剪。

class ImageUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick
  ...
  version :t do
    process :cropper
    process :resize_to_fill => [75, 75]
  end
  ...
  def cropper
    manipulate! do |img| 
      img = img.crop "#{model.crop_x}x#{model.crop_y}+#{model.crop_w}+#{model.crop_h}"
      img
    end 
  end

end

我遇到的问题是,如果我们没有任何设置但我不知道将这个逻辑放在哪里,我需要计算一些默认的裁剪值。我尝试将它放在我的照片模型(上传器安装到)中的 before_validation 中,但这似乎是在裁剪函数执行后调用的。我在想它要么需要在 ImageUploader 文件中,要么需要在创建拇指之前发生的一些回调中。

4

1 回答 1

10

你可以这样做:

process :cropper

def cropper
  manipulate! do |img|
    if model.crop_x.blank?
      image = MiniMagick::Image.open(current_path)
      model.crop_w = ( image[:width] * 0.8 ).to_i
      model.crop_h = ( image[:height] * 0.8 ).to_i
      model.crop_x = ( image[:width] * 0.1 ).to_i
      model.crop_y = ( image[:height] * 0.1 ).to_i
    end
    img.crop "#{model.crop_w}x#{model.crop_h}+#{model.crop_x}+#{model.crop_y}"
  end 
end

我正在运行与我的一个应用程序中的代码等效的代码。

于 2012-01-19T17:45:10.747 回答