Skip to content

Instantly share code, notes, and snippets.

@jmahmood
Created February 14, 2012 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmahmood/1824366 to your computer and use it in GitHub Desktop.
Save jmahmood/1824366 to your computer and use it in GitHub Desktop.
Resize Images in Python
#!/usr/bin/env python
# This is intended as a quick and dirty image resizer. It doesn't even check to see if the filename is already in use. I
# don't suggest it for production use without changes.
# Stashing it here for future improvements.
import Image
import sys
import os
def resize_image_width_ratio(filename, new_filename, max_width=800):
image = False
try:
image = Image.open(filename)
except:
return False
width,height = image.size
ratio = 1
if width > max_width:
ratio = float(width) / float(max_width)
new_width = int(float(width) / ratio)
new_height = int(float(height) / ratio)
img = image.resize((new_width, new_height), Image.ANTIALIAS)
out = file(new_filename, "w")
try:
img.save(out, "PNG")
finally:
out.close()
return True
def main():
filename, extention = os.path.splitext(sys.argv[1])
thumb = filename + "_jbmthumb.png"
resize_image_width_ratio(sys.argv[1], thumb, 100)
#This idiom means the below code only runs when executed from command line
if __name__ == '__main__':
main()
# Rename all files under a directory
# find . -name "*.jpg" -exec image_resize.py {} \;
# Incidentally, if you are on a mac and cannot install PIL:
# You need to set the GCC environmental variable.
# sudo su
# export ARCHFLAGS="-arch i386 -arch x86_64#
# easy_install pip
# pip install pil
#
# That was 45-50 minutes of desperate googling FYI.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment