1

i've got the following example where I wish to resize an image using Pillow.

As you can see I have a new width being passed in by the user, but no height. How would I work out the new height for this image, whilst maintaining the same aspect ratio?

The images are not squares, they are rectangles, so the height and width wont be the same.

    orig_image = Image.open(get_full_path(file.relative_path))
    new_width = int(request.args.get('w'))

    # TODO resize properly, we need to work out new image height
    resized_image = orig_image.resize((new_width, ), Image.ANTIALIAS)
ChrisB
  • 123
  • 5
  • 13
  • 1
    Does this answer your question? [Does Python PIL resize maintain the aspect ratio?](https://stackoverflow.com/questions/2232742/does-python-pil-resize-maintain-the-aspect-ratio) – Dmitry Leiko Aug 12 '20 at 08:43
  • @Dmitry This does not answer my question. I'd need to work out the new height based on the new width variable passed in and maintain the same aspect ratio as before. My images are not squares, so the new height and width wont be the same – ChrisB Aug 12 '20 at 08:48

1 Answers1

6

It sounds like you want to grab the original aspect ratio from the original image like so:

aspect_ratio = orig_image.height / orig_image.width

Once you then receive the the new_width you can calculate the new_height like so:

new_height = new_width * aspect_ratio

Then you can resize the image correctly:

resized_image = orig_image.resize((new_width, new_height), Image.ANTIALIAS)

Or to put it all together:

orig_image = Image.open(get_full_path(file.relative_path))
aspect_ratio = orig_image.height / orig_image.width 

new_width = int(request.args.get('w'))
new_height = new_width * aspect_ratio

resized_image = orig_image.resize((new_width, new_height), Image.ANTIALIAS)
tfv
  • 6,016
  • 4
  • 36
  • 67
S.D.
  • 2,486
  • 1
  • 16
  • 23
  • So I did try something like this but this often results in the image width being smaller than the image height. As these images are rectangles, that means you get a really stretched out and blurry image. – ChrisB Aug 12 '20 at 09:01
  • Can you share this code? That shouldn't happen as you are respecting the original relation between width and height here. – S.D. Aug 12 '20 at 09:12