How do I resize an image using PIL and maintain its aspect ratio?

后端 未结 20 2104
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:30

Is there an obvious way to do this that I\'m missing? I\'m just trying to make thumbnails.

20条回答
  •  醉梦人生
    2020-11-22 03:06

    Have updated the answer above by "tomvon"

    from PIL import Image
    
    img = Image.open(image_path)
    
    width, height = img.size[:2]
    
    if height > width:
        baseheight = 64
        hpercent = (baseheight/float(img.size[1]))
        wsize = int((float(img.size[0])*float(hpercent)))
        img = img.resize((wsize, baseheight), Image.ANTIALIAS)
        img.save('resized.jpg')
    else:
        basewidth = 64
        wpercent = (basewidth/float(img.size[0]))
        hsize = int((float(img.size[1])*float(wpercent)))
        img = img.resize((basewidth,hsize), Image.ANTIALIAS)
        img.save('resized.jpg')
    

提交回复
热议问题