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

后端 未结 20 1849
-上瘾入骨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:48

    This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change "basewidth" to any other number to change the default width of your images.

    from PIL import Image
    
    basewidth = 300
    img = Image.open('somepic.jpg')
    wpercent = (basewidth/float(img.size[0]))
    hsize = int((float(img.size[1])*float(wpercent)))
    img = img.resize((basewidth,hsize), Image.ANTIALIAS)
    img.save('sompic.jpg') 
    

提交回复
热议问题