【问题标题】:How to crop image manually with paperclip?如何使用回形针手动裁剪图像?
【发布时间】:2015-02-06 17:07:13
【问题描述】:

我正在使用 Rails 4.2 和 Mongoid 构建一个网站。我正在使用mongoid-paperclip,我正在尝试将图像裁剪为正方形,同时保留短边的尺寸(因此图像将填充整个正方形)。这是我的自定义处理器:

module Paperclip
  class Cropper < Thumbnail
    def initialize(file, options = {}, attachment = nil)
      super
      @preserved_size = [@current_geometry.width, @current_geometry.height].min
      @current_geometry.width = @preserved_size
      @current_geometry.height = @preserved_size
     end

    def target
      @attachment.instance
    end

    def transformation_command
      if crop_command
        crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ')
      else
        super
      end
    end

    def crop_command
      ["-crop", "#{@preserved_size}x#{@preserved_size}+#{@preserved_size}+#{@preserved_size}"]
    end
  end
end

并且它所附加的模型看起来有这样一行:

has_mongoid_attached_file :image, styles: {square: {processors: [:cropper]}}

但它似乎不起作用。保存了名为“square”的图像版本,但它与原始图像相同。我怎样才能让它工作?

【问题讨论】:

    标签: ruby-on-rails image ruby-on-rails-4 paperclip minimagick


    【解决方案1】:

    我能够在不使用回形针处理器的情况下解决此问题。在我的模型中,我使用 lambda 为图像指定了 styles

    has_mongoid_attached_file :image, styles: lambda {|a|
                                                tmp = a.queued_for_write[:original]
                                                return {} if tmp.nil?
                                                geometry = Paperclip::Geometry.from_file(tmp)
                                                preserved_size = [geometry.width.to_i, geometry.height.to_i].min
                                                {square: "#{preserved_size}x#{preserved_size}#"}
                                              }
    

    请注意,尺寸末尾的# 确保裁剪后的图像始终是指定尺寸,而不是仅仅缩小图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2010-11-04
      • 2015-02-25
      相关资源
      最近更新 更多