载波裁剪 [英] Carrierwave Cropping
问题描述
我有一个CarrierWave ImageUploader,它可以根据模型中的值(crop_x,crop_y,crop_w和crop_h)创建几个需要裁剪的原始图像版本。
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
我遇到的问题是我如果我们没有任何设置,则需要计算一些默认的裁剪值,但我不知道该逻辑放在哪里。我试过在before_validation中将其放入我的Photo模型(已将其上传到上传器中)中,但这似乎在执行cropper函数之后被调用。我在想它要么需要在ImageUploader文件中,要么需要在创建缩略图之前发生的某些回调中。
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.
推荐答案
您可以执行以下操作:
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.
这篇关于载波裁剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!