Created
January 28, 2012 07:25
-
-
Save omsai/1693206 to your computer and use it in GitHub Desktop.
Crop and resize using PIL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Resizes images in current folder for vandanashourie.com | |
# Saves images into sub-folders: | |
# ./tabs-square <- 150x150 thumbnauls | |
# ./full <- 725x525 images | |
import os, sys | |
import Image | |
import math | |
def square(coordinates): | |
''' | |
Crops a 4-tuple into the largest center square | |
e.g.: | |
In = (0, 0, 100, 150) | |
Out = (0, 25, 100, 125) | |
''' | |
x0, y0, x1, y1 = coordinates | |
diff = int(math.fabs(x1 - y1) / 2) | |
if x1 > y1: | |
x0 = int(diff) | |
x1 = int(x1 - diff) | |
else: | |
y0 = int(diff) | |
y1 = int(y1 - diff) | |
return (x0, y0, x1, y1,) | |
listing = os.listdir(os.getcwd()) | |
for infile in listing: | |
''' | |
Crop image to square, then make 150x150 thumbnail | |
''' | |
size = 150, 150 | |
outfile = "tabs-square/" + os.path.splitext(infile)[0] + ".jpg" | |
try: | |
im = Image.open(infile) | |
data = im.getbbox() | |
data = square(data) | |
im = im.transform(size, Image.EXTENT, data) | |
im.thumbnail(size, Image.ANTIALIAS) | |
im.save(outfile, "JPEG") | |
except IOError: | |
print "Cannot create thumbnail for '%s'" % infile | |
''' | |
Make 725x525 image | |
''' | |
size = 725, 525 | |
outfile = "full/" + os.path.splitext(infile)[0] + ".jpg" | |
try: | |
im = Image.open(infile) | |
im.thumbnail(size, Image.ANTIALIAS) | |
im.save(outfile, "JPEG") | |
except IOError: | |
print "Cannot create smaller file for '%s'" % infile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment