简体   繁体   English

Rails设置了新的尺寸图像回形针

[英]Rails set new dimentions image paperclip

Is there any way to set new dimensions to my_image and save it to AWS S3 ? 有什么方法可以将新尺寸设置为my_image并将其保存到AWS S3

I have 我有

my_image = Post.last.photo.image

geometry = Paperclip::Geometry.from_file(my_image.url)

so i want to set new geometry and save it 所以我想设置新的几何并保存

geometry = 'my params'
my_image.save

Of course i have my 我当然有

  has_attached_file :image, :styles => { :large => "220x" ..other styles}

My main goal set new dimensions during cropping photo with Jcrop 我的主要目标是在使用Jcrop裁剪照片期间设定新的尺寸

so when i receive new params like my_params => "crop_x"=>"83", "crop_y"=>"24", "crop_w"=>"76", "crop_h"=>"76" set it as new style inside has_attached_file 所以当我收到像my_params => "crop_x"=>"83", "crop_y"=>"24", "crop_w"=>"76", "crop_h"=>"76"之类的新参数时,将其设置为新样式在has_attached_file里面

You can do that easily, 您可以轻松做到这一点,

Declare attribute accessors for the crop dimensions 声明作物尺寸的属性访问器

attr_accessor :crop_x, :crop_y, :crop_w, :crop_h

Then you need to override the processor, create cropper.rb in /lib/paperclip_processors and add following code 然后,您需要覆盖处理器,在/lib/paperclip_processors cropper.rb中创建cropper.rb ,并添加以下代码

module Paperclip
  class Cropper < Thumbnail
    def transformation_command
      if crop_command
        crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ') # super returns an array like this: ["-resize", "100x", "-crop", "100x100+0+0", "+repage"]
      else
        super
      end
    end

    def crop_command
      target = @attachment.instance
      if target.cropping?
        ["-crop", "#{target.crop_w}x#{target.crop_h}+#{target.crop_x}+#{target.crop_y}"]
      end
    end
  end
end

Now in the model you can do this 现在,您可以在模型中执行此操作

has_attached_file :image, styles: { large: "800X800>" }, default_url: "/images/:style/missing.png", :processors => [:cropper]
after_save :reprocess_image, if: :cropping?

def cropping?
  !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?
end

def reprocess_image
  image.assign(image)
  image.save
end

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM