DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Im a freelance developer for Web apps and Artificial intelligence (in Python). Budy K. has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Resize thousands of images with Python

  • submit to reddit
import PIL
from PIL import Image
import os
import sys

def readf():

        input_dir  = str(sys.argv[1].rstrip('/'))  #path to img source folder
        img_size   = str(sys.argv[2])  #The image size (128, 256,etc)
        output_dir  = str(sys.argv[3].rstrip('/')) #output directory
        print "starting...."
        print "Colecting data from %s " % input_dir
        tclass = [ d for d in os.listdir( input_dir ) ]
        counter = 0
        strdc = ''
        hasil = []
        for x in tclass:
           list_dir =  os.path.join(input_dir, x )
           list_tuj = os.path.join(output_dir+'/', x+'/')
           if not os.path.exists(list_tuj):
           if os.path.exists(list_tuj):
               for d in os.listdir(list_dir):
                       img ='/'+x,d))
                       img = img.resize((int(img_size),int(img_size)),Image.ANTIALIAS)
                       fname,extension = os.path.splitext(d)
                       newfile = fname+extension
                       if extension != ".jpg" :
                           newfile = fname + ".jpg"
                       print "Resizing file : %s - %s " % (x,d)
                   except Exception,e:
                        print "Error resize file : %s - %s " % (x,d)
               counter +=1
    except Exception,e:
        print "Error, check Input directory etc : ", e

Image resizer  

I created the script to resize thousands images in a single-run Python command in Linux (Ubuntu). This will also work in Windows i guess. It can resize thousands of images ( I run it before for > 50K images)

Suppose we have images stored in Folder structures like this : 


----  Tigers





---- Cats





---- n






ans so on. 

Run the script with this steps : 

1. Open your terminal, and type

2. python {img source folder} {the size you want the image to be} {destination folder}

   example : 

   python /home/ubuntu/images/ 128 /home/ubuntu/new_images

3. Drink your coffee and watch the terminal running the process 

1. Install PIL image if you dont have one ( another library considered faster than this)
2. ANTIALIAS and quality=90 is to prevent the image from downgrading quality for Down-Scalling
3. This code works for Down-Scalling resize , yo can use another method beside ANTIALIAS for Free-Scalling
4. Images will be converted to .jpg extension ( its up to you, you can change it your way)
5. If you have different folder structures from above example, modify the code