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

后端 未结 20 1858
-上瘾入骨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 02:56

    Open your image file

    from PIL import Image
    im = Image.open("image.png")
    

    Use PIL Image.resize(size, resample=0) method, where you substitute (width, height) of your image for the size 2-tuple.

    This will display your image at original size:

    display(im.resize((int(im.size[0]),int(im.size[1])), 0) )
    

    This will display your image at 1/2 the size:

    display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )
    

    This will display your image at 1/3 the size:

    display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )
    

    This will display your image at 1/4 the size:

    display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )
    

    etc etc

提交回复
热议问题