tags:

views:

46

answers:

1

Hi all,

I am trying to resize an image with Rmagick and if I use the resize_to_fit method to always resize the height first, preferring that to width, but it seems as if most of my images are being resized to width first. IS there anyway using the resize_to_fit method to tell it "prefer height over width"?

A: 

A few thoughts and some code.

What differences do you see? How can you tell it's width first? I don't see a case where the end result should be a different size, if it's a quality problem an example might help.

It doesn't look like the api exposes a way to stretch one way and then another but we can certainly make a method or two to give it a try. There are two approaches below, the first, two_step_resize resizes in one direction and the the other. The second, resize_with_rotate rotates the image, resizes it, and then rotates it back.

For the examples I ran it through I don't see any oddness in either solution.

require 'RMagick'


#Change the size in two steps, height first then width
def two_step_resize(img, filename, max_x, max_y)
  x = img.columns
  y = img.rows

  #make sure it's a float w/ the 1.0*
  ratio = (1.0*x)/y  

  new_y = max_y
  new_x = ratio * new_y

  if (new_x > max_x)
    new_x = max_x
    new_y = new_x / ratio
  end

  # do the change in two steps, first the height
  img.resize!(x, new_y);
  #then the width
  img.resize!(new_x, new_y)

  #save it, with the least compression to get a better image
  res.write(filename){self.quality=100}

end

#spin the image before resizing
def resize_with_rotate(img, output_filename, max_x, max_y)
  res = img.rotate(90).resize_to_fit(max_y, max_x).rotate(-90)
  res.write(output_filename){self.quality=100}
end

img = Magick::Image.read(filename).first
two_step_resize(img, "2-step.jpg", 100, 200)

img = Magick::Image.read(filename).first
resize_with_rotate(img, "rotate.jpg", 100, 200)
Paul Rubel
actually, the best solution I found was to use resize_to_fill! to crop the image down to get the dimensions I wanted. I didn't understand that it doens't matter what the width or the height is, whichever was bigger would be the num I scaled to, since it would keep the aspect ratio. I will give you the points for being the one to answer, though.
tesmar