Friday, January 3, 2014

Resize Image in python

#!/usr/bin/python

"""

Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).

The proper size is oldsize*ratio.

There is of course also a library method to do this: the method Image.thumbnail.
Below is an (edited) example from the PIL documentation.

"""


import os, sys
import Image
import re
import shutil


size = 1224, 1632


dirDes= "out-dir/"

if os.path.exists(dirDes):
    pass
else:
    os.system('mkdir ' + dirDes)

if len(sys.argv) == 1:
    print "use -h for help"
elif sys.argv[1] == "-h":
    print "example: resize all image in directory"
    print "./resize-image.py -d inputDirectory"
    print "example: resize a file"
    print "./resize-image.py -f inputFile"
    print "*" * 25
    print "output file will be in out-dir"
elif sys.argv[1] == "-d":
    dirName = sys.argv[2]
    for dirname, dirnames, filenames in os.walk(dirName):
        for filename in filenames:
            outfile = os.path.splitext(filename)[0] + ".thumbnail"
            infile = dirName + "/" + filename
            if filename != outfile:
                try:
                    im = Image.open(infile)
                    im.thumbnail(size, Image.ANTIALIAS)
                    im.save(dirDes + outfile, "JPEG")
                except IOError:
                    print "cannot create thumbnail for '%s'" % infile
elif sys.argv[1] == "-f":
    filename = sys.argv[2]
    outfile = os.path.splitext(filename)[0] + ".thumbnail"
    infile = filename
    if filename != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(dirDes + outfile, "JPEG")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile

No comments:

Post a Comment