开发者

RMagick: scale and resize image for thumbnail

开发者 https://www.devze.com 2023-02-05 00:56 出处:网络
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. Ideall

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 t开发者_C百科o 100 (aspect ratio) and then fill up the smaller edge with white.

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

I dont use Paperclip or Rails, just RMagick.


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)


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.


It seems you want to use change_geometry...

0

精彩评论

暂无评论...
验证码 换一张
取 消