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

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

    Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).

    The proper size is oldsize*ratio.

    There is of course also a library method to do this: the method Image.thumbnail.
    Below is an (edited) example from the PIL documentation.

    import os, sys
    import Image
    
    size = 128, 128
    
    for infile in sys.argv[1:]:
        outfile = os.path.splitext(infile)[0] + ".thumbnail"
        if infile != outfile:
            try:
                im = Image.open(infile)
                im.thumbnail(size, Image.ANTIALIAS)
                im.save(outfile, "JPEG")
            except IOError:
                print "cannot create thumbnail for '%s'" % infile
    

提交回复
热议问题