ChrisB
ChrisB

Reputation: 153

Pillow Resize Image - Maintaing Aspect Ratio

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)

Upvotes: 1

Views: 5101

Answers (1)

S.D.
S.D.

Reputation: 2951

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)

Upvotes: 6

Related Questions