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
http://askubuntu.com/questions/156484/how-do-i-install-python-imaging-library-pil

For Mac users, this might be helpful
http://stackoverflow.com/questions/19532125/cant-install-pil-after-mac-os-x-10-9

Code:

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):
    os.makedirs(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)                    
        try:
            img = Image.open(file)
            img.thumbnail(size)
            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!
http://effbot.org/imagingbook/introduction.htm

About Melvin Dave Vivas

I currently live in Singapore and work as a Software Development Manager in an international bank. I enjoy programming and taking photos. You can also visit my Tech Blog @ www.melvinvivas.com

Comments