Carrierwave Cropping

余生颓废 提交于 2020-01-12 10:01:55

问题


I have an CarrierWave ImageUploader which creates a couple of versions of an original image that need to be cropped based on values in my model (crop_x, crop_y, crop_w, and 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

The problem that I'm having is that I need to calculate some default cropping values if we don't have any set but I don't know where to put this logic. I tried putting this in my Photo model (which the uploader is mounted to) in a before_validation but this seems to be called after the cropper function has executed. I'm thinking that It either needs to be in the ImageUploader file, or in some callback that occurs before the thumbs are created.


回答1:


You can do something like this:

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

I'm running code equivalent to that in one of my apps.



来源:https://stackoverflow.com/questions/6757359/carrierwave-cropping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!