public
Created

Resize Images in Python

  • Download Gist
image_resize.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#!/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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.