Carrierwave和Jcrop没有使用Minimagick进行裁剪

时间:2014-05-29 15:45:34

标签: ruby-on-rails carrierwave jcrop

我关注如何使用Carrierwave和Jcrop裁剪图像的Ryan Bates教程。

但是,图像没有被裁剪。 x,y,w,h值在参数中传递,但没有进行裁剪。我正在使用Minimagick。我真的很感谢某人的帮助。

我在Stackoverflow中遇到了类似的问题,但没有一个能给出一个好的解决方案。 谢谢

Photo_uploader

  process :resize_to_fit => [800,800]

  version :big do
    process :resize_to_limit => [800,600]
    process :convert => 'jpg'
  end

  version :thumb, :from_version => :big do
    process :crop
    resize_to_fill(100,100)
  end

  def crop
    if model.crop_x.present?
      resize_to_limit(600, 600)
      manipulate! do |img|
        x = model.crop_x.to_i
        y = model.crop_y.to_i
        w = model.crop_w.to_i
        h = model.crop_h.to_i
        img.crop "#{model.crop_x}x#{model.crop_y}+#{model.crop_w}+#{model.crop_h}"
        img
      end
    end
  end

查看

<%= image_tag @photo.photo_url(:big), id: "cropbox" %>

模型

  mount_uploader :photo, PhotoUploader
  attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
  before_create :crop_spot
  after_update :crop_spot

更新

#Cropping spots
def crop_spot
  photo.recreate_versions! if crop_x.present?
end

2 个答案:

答案 0 :(得分:0)

img.crop方法不会更改图像,但会返回一个新图像。因此,要么使用img.crop!来编辑图像,要么删除最后的img,以便修改已编辑的图像。

然后crop方法变为

def crop
  if model.crop_x.present?
    resize_to_limit(600, 600)
    manipulate! do |img|
      x = model.crop_x.to_i
      y = model.crop_y.to_i
      w = model.crop_w.to_i
      h = model.crop_h.to_i
      img.crop "#{model.crop_x}x#{model.crop_y}+#{model.crop_w}+#{model.crop_h}"
    end
  end
end

答案 1 :(得分:0)

对我而言,它就是这样的:

include CarrierWave::MiniMagick

version :thumb do
  process :resize_to_fit => [Cover::IMAGE_WIDTH, -1] # '-1' means that height is infinite (this is works for minimagick, but for rmagick it should be '10000').
  process :manual_crop
  process :resize_to_fill => [340, 191]
end

version :big do
  process :resize_to_fit => [Cover::IMAGE_WIDTH, -1]
  process :manual_crop
  process :resize_to_fill => [Cover::IMAGE_WIDTH, Cover::IMAGE_HEIGHT]
end

def manual_crop
  return if model.crop_coords.blank?
  manipulate! do |img|
    img.crop "#{model.crop_coords['w'].to_i}x#{model.crop_coords['h'].to_i}+#{model.crop_coords['x'].to_i}+#{model.crop_coords['y'].to_i}!"
    img
  end
end

crop_coords是JCrop返回的坐标(但我们不需要x2和y2,所以我不在这里使用它们) 考虑到格式为&#34; WxH + X + Y&#34;。 请参阅http://www.imagemagick.org/script/command-line-processing.php#geometryhttp://www.imagemagick.org/script/command-line-options.php#crop