Image Manipulation

This simple script below resizes a directory of images and center-crops them to 300x300.


from PIL import Image
import os,glob
basesize = 250

source_folder = os.getcwd()

for file in glob.glob("*.jpg"):

    img = Image.open(file)
    w,h = img.size

    hsize = int((basesize / float(w))* h)
    wsize = int((basesize / float(h))* w)

    if hsize > wsize:
        img = img.resize((basesize, hsize), Image.ANTIALIAS)
    else:
        img = img.resize((wsize, basesize), Image.ANTIALIAS)

    w,h = img.size

    left = int((w - basesize)/2)
    top = int((h - basesize)/2)
    right = int((w + basesize)/2)
    bottom = int((h + basesize)/2)

    img = img.crop((left,top,right,bottom))

    os.chdir(os.getcwd() + "\\output")
    img.save(file[:-4]+"_thumb.jpg" ,  "JPEG")
    os.chdir(source_folder)

    
Back to Projects