Rmagick auto-scale with aspect ratio

Is there a way to scale both the image in rmagick, where I set the width, and auto-scale the height so that the image contains the same proportions?

+3
source share
1 answer

I use the resize_to_fit method, which will use the parameters provided as the maximum width / height, but preserve the aspect ration. So something like this:

@scaled = @image.resize_to_fit 640 640

This ensures that the width or height does not exceed 640, but will not stretch the image, which makes it funny. So you can get 640x480 or 480x640. There is also resize_to_fit! method that translates into place

, . - :

@img = Magick::Image::read(file_name).first

def resize_by_width image new_width  
  @new_height = new_width * image.x_resolution.to_f / image.y_resolution.to_f
  new_image = image.scale(new_width, new_height)

  return new_image
end

@resized = resize_by_width @img 1024

, !

+4

Source: https://habr.com/ru/post/1772242/


All Articles