RMagick: scale and resize image for thumbnail

隐身守侯 提交于 2019-12-06 07:14:09

I've done it with merging the resized image with a new 100x100 image. Thats 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)

After playing with it for a while I got Fu86's composite trick to work like so:

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 seems to work better than CopyCompositeOp, which turned part of my background black for some reason.

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")

Note: on heroku, which as of this posting uses imagemagick 6.5.7-8, I needed to multiply the x and y translations by -1 (and send positive numbers). Version 6.8.0-10 expects negative numbers.

Douglas Perkins

It seems you want to use change_geometry...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!