I'm trying to create something with Pillow. The Problem is the following. I have a photo like with a resolution of 612 * 563.
I would like to change the height of this photo while the Proportion stays like in picture one. If I try to change the resolution for instance to 612 * 500 the tire gets wider.
That's not how I want it. Is there a way in pillow how I can change the resolution (height) of the photo while keeping the original proportions?
I have now added the following code, which was given by Kris. Unfortunately it still does not seem to work.
Python does not say that theres a mistake but it does not save a file at all. The new picture should be saved under the name "ReifenTest1" or am I wrong?
CodePudding user response:
Well, you need to resize maintaining aspect ratio. Then it will be ok. See an example here.
def auto_resize(image_im: Image.Image, max_height):
if image_im:
width, height = image_im.size # get the current size
if height > max_height:
aspect = width / height # find the aspect ratio
r_height = max_height # Set your needed height
r_width = int(r_height * aspect) #Calcualte the width for lock on proportions
image_im = image_im.resize((r_width, r_height)) # resize then!
return image_im
CodePudding user response:
You can just use the thumbnail method from PIL to obtain a resized image that keeps the original aspect ratio.
from PIL import Image
target_width = 612
target_height = 500
maxsize = (target_width, target_height)
path_to_the_image = /path/to/the/image
image = Image.open(path_to_the_image)
image.thumbnail(maxsize, Image.ANTIALIAS)
image.save("resized-image.*") # change the * for png/jpeg/etc