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

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

Asked on November 9, 2018 in Python.
Add Comment


  • 3 Answer(s)

      Define a most size. Then, calculate a size magnitude relation by taking min(maxwidth/width, maxheight/height).
     

      The proper size is oldsize*ratio.

      There is after all additionally a library methodology to try to to this: the tactic Image.thumbnail.
    Below is associate (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
    
    Answered on November 9, 2018.
    Add Comment

      This script can size a picture (somepic.jpg) victimisation PIL (Python Imaging Library) to a dimension of three hundred pixels and a height proportional to the new dimension.

      It will this by crucial what share three hundred pixels is of the initial dimension (img.size[0]) and so multiplying the initial height (img.size[1]) by that share. modification “basewidth” to the other variety to alter the default dimension of your pictures:

    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')
    
    Answered on November 9, 2018.
    Add Comment

      For Resizing width:

    new_width = 680
    new_height = new_width * height / width
    

      Resizing height:

    new_height = 680
    new_width = new_height * width / height
    

      Then just:

    img = img.resize((new_width, new_height), Image.ANTIALIAS)
    
    Answered on November 9, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.