Created
August 13, 2013 13:22
-
-
Save yanmhlv/6221018 to your computer and use it in GitHub Desktop.
thumbs
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
#!/usr/bin/env python | |
# coding: utf-8 | |
from PIL import Image | |
import sys, os | |
#@app.route("/thumbs") | |
def thumbs(): | |
# not good (type of values) but something like this | |
file = request.args.get('file', None) | |
width = request.args.get('width', 120) | |
height = request.args.get('height', 90) | |
quality = request.args.get('height', 70) | |
crop = request.args.get('crop', False) | |
# image | |
img = Image.open(file) | |
newpath = "" | |
out = file(newpath, "w") | |
resize(img, (width, height), crop, out, quality) | |
return send_file(out) | |
def resize(img, box, fit, out, quality=75): | |
'''Downsample the image. | |
script example : | |
>>> import Image, os, sys | |
>>> for filename in sys.argv[1:]: | |
>>> img = Image.open(filename).resize( (200,200) ) | |
>>> out = file(os.path.splitext(filename)[0]+"_thumb.jpg", "w") | |
>>> try: | |
>>> img.save(out, "JPEG") | |
>>> finally: | |
>>> out.close() | |
@param img: Image - an Image-object | |
@param box: tuple(x, y) - the bounding box of the result image | |
@param fix: boolean - crop the image to fill the box | |
@param out: file-like-object - save the image into the output stream | |
''' | |
#preresize image with factor 2, 4, 8 and fast algorithm | |
factor = 1 | |
while img.size[0] / factor > 2 * box[0] and img.size[1] * 2 / factor > 2 * box[1]: | |
factor *= 2 | |
if factor > 1: | |
img.thumbnail((img.size[0] / factor, img.size[1] / factor), Image.NEAREST) | |
#calculate the cropping box and get the cropped part | |
if fit: | |
x1 = y1 = 0 | |
x2, y2 = img.size | |
wRatio = 1.0 * x2 / box[0] | |
hRatio = 1.0 * y2 / box[1] | |
if hRatio > wRatio: | |
y1 = y2 / 2-box[1] * wRatio / 2 | |
y2 = y2 / 2 + box[1] * wRatio / 2 | |
else: | |
x1 = x2 / 2-box[0] * hRatio / 2 | |
x2 = x2 / 2 + box[0] * hRatio / 2 | |
img = img.crop((x1, y1, x2, y2)) | |
#Resize the image with best quality algorithm ANTI-ALIAS | |
img.thumbnail(box, Image.ANTIALIAS) | |
#save it into a file-like object | |
img.save(out, "JPEG", quality = quality) | |
#resize | |
""" | |
<a href="{{ imagepath }}"> | |
<img src="{{ url_for('thumbs', file=imagepath, width=120, height=90) }}" | |
alt="" /> | |
</a> | |
""" | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
for filename in sys.argv[1:]: | |
img = Image.open(filename) | |
out = file(os.path.splitext(filename)[0] + '_thumb_%dx%d.jpg' % (120, 90), 'w') | |
resize(img, (120,90), False, out, 90) | |
else: | |
print "For make thumbs, please exec %s [filenames]" % __file__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment