Image RMagick:缩放缩略图的图像并调整其大小

Image RMagick:缩放缩略图的图像并调整其大小,image,rmagick,Image,Rmagick,我想调整图像的大小/比例。原件的尺寸与300x200或512x600不同。我想将图像大小调整为100x100,但不要从图像中裁剪任何内容或更改比率。理想情况下,图像将首先将长边缩放到100(纵横比),然后用白色填充较小的边 .---------. |- - - - -| | IMAGE | |- - - - -| '---------' 我不使用回形针或Rails,只使用RMagick。我将调整大小的图像与新的100x100图像合并。这肯定不是最好的方法,但它很有效: img=M

我想调整图像的大小/比例。原件的尺寸与300x200或512x600不同。我想将图像大小调整为100x100,但不要从图像中裁剪任何内容或更改比率。理想情况下,图像将首先将长边缩放到100(纵横比),然后用白色填充较小的边

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

我不使用回形针或Rails,只使用RMagick。

我将调整大小的图像与新的100x100图像合并。这肯定不是最好的方法,但它很有效:

img=Magick::Image.read(“file.png”)。首先
target=Magick::Image.new(100100)do
self.background_color='white'
结束
img.resize_到_fit!(100, 100)
composite(img,Magick::CenterGravity,Magick::CopyCompositeOp).write(“file small.png”)

似乎您想使用…

在玩了一段时间后,我得到了Fu86的合成技巧,如下所示:

img = Image.read("some_file").first().resize_to_fit!(width, height)
target = Image.new(width, height) do
    self.background_color = 'white'
end
target.composite(img, CenterGravity, AtopCompositeOp).write("some_new_file")
AtopCompositeOp
似乎比
CopyCompositeOp
工作得更好,因为某种原因,它将我的部分背景变为黑色

image = Magick::Image.read("filename").first
resized = image.resize_to_fit(width, height)     # will maintain aspect ratio, so one of the resized dimensions may be less than the specified dimensions
resized.background_color = "#FFFFFF"             # without a default, background color will vary based on the border of your original image
x = (resized.columns - width) / 2                # calculate necessary translation to center image on background
y = (resized.rows - height) / 2
resized = resized.extent(width, height, x, y)    # 'extent' fills out the resized image if necessary, with the background color, to match the full requested dimensions. the x and y parameters calculated in the previous step center the image on the background.
resized.write("new_filename")
注意:在heroku上,我需要将x和y的翻译数乘以-1(并发送正数)。6.8.0-10版需要负数