0

我使用 CarrierWave,我想将图像的大小调整为 220 像素的宽度和 220 像素的最大高度。如果我使用process :resize_to_fit => [220,220]它可能是宽度不是 220px。我能做些什么?

4

2 回答 2

3

如果我正确解释了这个问题:

  • 对于肖像图像(例如 480 像素宽,640 像素高),您可能希望将其缩小到 220 像素宽,然后将其裁剪到 220 像素高,从而生成方形图像。

  • 对于横向图像,您可能希望将其缩小到 220 像素宽(因此高度将小于 220 像素)。

如果这是正确的,您需要一个两步过程:

  1. 调整为 220px 宽,保留纵横比
  2. 裁剪到 220px 高(如果是纵向)

manipulate!您可以通过使用命令编写自己的处理器来做到这一点(请参阅CarrierWave 自己的以获得一些灵感)。

我想这大致就是你所追求的

process :resize => [220, 220]

protected

def resize(width, height, gravity = 'Center')
  manipulate! do |img|
    img.combine_options do |cmd|
      cmd.resize width.to_s
      if img[:width] < img[:height]
        cmd.gravity gravity
        cmd.background "rgba(255,255,255,0.0)"
        cmd.extent "#{width}x#{height}"
      end
    end
    img = yield(img) if block_given?
    img
  end
end
于 2013-01-09T15:23:32.500 回答
2

对安迪 H 的回答进行了改进:

process :resize => [220, 220]

protected

def resize(width, height, gravity = 'Center')
  manipulate! do |img|
    img.combine_options do |cmd|
      cmd.resize "#{width}"
      if img[:width] < img[:height]
        cmd.gravity gravity
        cmd.background "rgba(255,255,255,0.0)"
        cmd.extent "#{width}x#{height}"
      end
    end
    img = yield(img) if block_given?
    img
  end
end
于 2013-01-09T19:25:30.023 回答