RMagick:缩放和调整缩略图的图像大小

问题描述:

我要调整图像的大小/比例.原稿的尺寸不一样,例如300x200或512x600.我想将图像调整为100x100,但不要从图像中裁剪任何东西或更改比例.理想情况下,图像将首先将长边缘缩放为100(长宽比),然后用白色填充较小的边缘.

I want to resize/scale an image. The originals have not the same dimensions like 300x200 or 512x600. I want to resize the image to 100x100 but DONT crop anything from the image or change ratio. Ideally the image will be first scale the long edge to 100 (aspect ratio) and then fill up the smaller edge with white.

 .---------.
 |- - - - -|
 |  IMAGE  |
 |- - - - -|
 '---------'

我不使用Paperclip或Rails,仅使用RMagick.

I dont use Paperclip or Rails, just RMagick.

我已经完成了将调整大小后的图像与新的100x100图像合并的操作.肯定不是最好的方法,但是它可以工作:

I've done it with merging the resized image with a new 100x100 image. That's for sure not the best way but it works:

img = Magick::Image.read("file.png").first
target = Magick::Image.new(100, 100) do
  self.background_color = 'white'
end
img.resize_to_fit!(100, 100)
target.composite(img, Magick::CenterGravity, Magick::CopyCompositeOp).write("file-small.png)