Best Pracice to Python Resize Images with Pillow – Python Tutorial

By | August 30, 2020

Resizing an image has three ways:

To a fixed width and height, such as 1000*2000 to 512 * 512.  The ratio of width and height usually is changed.

To set width to a fixed value, the height is changed with ratio.

To set height to a fixed value, the width is changed with ratio.

In this tutorial, we will introduce you how to resize an image with these three situations.

python resize an image with pillow

Import library

from PIL import Image

Open an image with pillow

img = Image.open(f)

Resize an image to a fixd width and height

if fixed:
        img = img.resize((fixed[0], fixed[1]), Image.ANTIALIAS)

Resize width to a fixed value, height is changed with ratio

elif basewidth:  
        wpercent = (basewidth / float(img.size[0])) 
        hsize = int((float(img.size[1]) * float(wpercent)))
        img = img.resize((basewidth, hsize), Image.ANTIALIAS)

Resize height to a fixed value, width is changed with ratio

elif baseheight:
        hpercent = (baseheight / float(img.size[1]))
        wsize = int((float(img.size[0]) * float(hpercent)))
        img = img.resize((wsize, baseheight),Image.ANTIALIAS)

Save new image

img.save(f)

Then, a full code example is here.

def resizeImage(f, fixed = None, basewidth = None, baseheight = None):
    img = Image.open(f)
    if fixed:
        img = img.resize((fixed[0], fixed[1]), Image.ANTIALIAS)
    elif basewidth:  
        wpercent = (basewidth / float(img.size[0])) 
        hsize = int((float(img.size[1]) * float(wpercent)))
        img = img.resize((basewidth, hsize), Image.ANTIALIAS)
    elif baseheight:
        hpercent = (baseheight / float(img.size[1]))
        wsize = int((float(img.size[0]) * float(hpercent)))
        img = img.resize((wsize, baseheight),Image.ANTIALIAS)
    img.save(f)
    return f

You can use this resizing function in your application.

Leave a Reply