Skip to content

Instantly share code, notes, and snippets.

@selwin
Created April 4, 2010 11:01
Show Gist options
  • Save selwin/355320 to your computer and use it in GitHub Desktop.
Save selwin/355320 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os
from os.path import join
from PIL import Image
#This script walks through subdirectories, checks if image is valid and if it is, saves the image in JPG format with quality setting of 65
for root, dirs, files in os.walk('.'):
#print "Current directory", root
#print "Sub directories", dirs
#for directory in dirs:
for filename in files:
path = os.path.join(root, filename)
try:
#Verify that file is valid image
trial_image = Image.open(path)
trial_image.verify()
print path + ' is a valid image file'
#And now resize the image
image = Image.open(path)
file_name = os.path.splitext(path)[0]
resized_filename = file_name.replace(' ', '_')[2:] + '_resized' + '.jpg'
print('Resizing %s...') % file_name
image.convert('RGB').save(resized_filename, 'JPEG', quality=65)
except ImportError:
# Under PyPy, it is possible to import PIL. However, the underlying
# _imaging C module isn't available, so an ImportError will be
# raised. Catch and re-raise.
raise
except IOError:
pass
except:
pass
#print "Files", files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment