调整大小时拍摄图像的中心部分

时间:2014-01-28 18:23:44

标签: ruby-on-rails ruby-on-rails-4 imagemagick minimagick

使用Carrierwave-MiniMagick-ImageMagick调整图像大小时出现问题。

我编写了自定义调整大小的方法,因为我需要将两个图像合并在一起并对它们进行一些处理,因此MiniMagick的标准process方法是不够的。问题在于调整大小的方法。我需要拍摄图像的中心部分,但它会返回顶部。

enter image description here

def merge
  manipulate! do |img|
    img.resize '180x140^' # problem is here

    ...

    img
  end
end

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

我会按如下方式处理:

  • 将图像尺寸调整为180x180平方
  • 从顶部删除(180-140)/ 2
  • 从底部删除(180-140)/ 2

这样的事情应该这样做:

def merge
  manipulate! do |img|
    img.resize '180x180' # resize to 180px square
    img.shave '0x20' # Removes 20px from top and bottom edges

    img # Returned image should be 180x140, cropped from the centre
  end
end

当然,这假设您的输入图像始终是正方形。如果它不是正方形并且您已经将心脏设置为180x140比率,那么您可以执行以下操作:

def merge
  manipulate! do |img|
    if img[:width] <= img[:height]
      # Image is tall ...
      img.resize '180' # resize to 180px wide
      pixels_to_remove = ((img[:height] - 140)/2).round # calculate amount to remove
      img.shave "0x#{pixels_to_remove}" # shave off the top and bottom
    else
      # Image is wide
      img.resize 'x140' # resize to 140px high
      pixels_to_remove = ((img[:width] - 180)/2).round # calculate amount to remove
      img.shave "#{pixels_to_remove}x0" # shave off the sides
    end

    img # Returned image should be 180x140, cropped from the centre
  end
end

答案 1 :(得分:1)

这是resize_to_fill的作用:

  

调整图像大小以适合指定的尺寸,同时保留原始图像的纵横比。如有必要,请以较大的尺寸裁剪图像。

示例:

image = ImageList.new(Rails.root.join('app/assets/images/image.jpg'))
thumb = image.resize_to_fill(1200, 630)
thumb.write('thumb.jpg')

该方法采用第三个参数,即重力,但默认情况下为CenterGravity

答案 2 :(得分:0)

您应该使用crop代替resize

在这里查看裁剪命令的裁剪ImageMagick描述: http://www.imagemagick.org/script/command-line-options.php#crop

MiniMagick只是ImageMagick的包装器,因此所有参数都是相同的。