/ Technology

Python Script to Resize Photos

Here's a simple Python script I created to resize photos. Feel free to use, cheers!

The script resizes images to max 512px by 512px and moves the resized photos to a new folder called "resized". Since the resized images is copied to a new folder, we can retain the original filename.

This is actually my first taste of Python so please bear with me if I failed to follow any best practice.

I used the Python Imaging Library (PIL) so you need to install it before you can successfully run the script.

This might help for Ubuntu users

For Mac users, this might be helpful


import os, sys
from PIL import Image

size = 512, 512
resizedFolder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resized")
if not os.path.exists(resizedFolder):
for file in os.listdir("./"):
    if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith(".png") :       
        if file.endswith(".jpg"):
            outfile = os.path.splitext(file)[0] + ".jpg"
        if file.endswith(".jpeg"):       
            outfile = os.path.splitext(file)[0] + ".jpeg"
        if file.endswith(".png"):               
            outfile = os.path.splitext(file)[0] + ".png"
        newFolder = os.path.join(resizedFolder, outfile)                    
            img = Image.open(file)
            img.save(newFolder, "JPEG")
        except IOError, ioe:
            print "cannot resize", infile
            print str(ioe)

There are more cool stuff to explore using PIL. Here are some goodies!