#this is a copy from
http://www.web2pyslices.com/slice/show/1522/generate-a-thumbnail-that-fits-in-a-box#modules\smarthumb.py
from gluon import current
import os
try:
from PIL import Image
except:
import Image
def SMARTHUMB(image, box, fit=True, name="thumb"):
'''Downsample the image.
@param img: Image - an Image-object
@param box: tuple(x, y) - the bounding box of the result image
@param fit: boolean - crop the image to fill the box
'''
if image:
request = current.request
img = Image.open(request.folder + 'uploads/' + image)
#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 = int(y2 / 2 - box[1] * wRatio / 2)
y2 = int(y2 / 2 + box[1] * wRatio / 2)
else:
x1 = int(x2 / 2 - box[0] * hRatio / 2)
x2 = int(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)
img.thumbnail.show()
root, ext = os.path.splitext(image)
thumb = '%s_%s%s' % (root, name, ext)
#save it into a file-like object
img.save(request.folder + 'uploads/' + thumb)
return thumb
#models\db.py
Article = db.define_table('article',
Field("title"),
Field("article_text", "text"),
Field("picture", "upload", uploadfoder='uploads'),
Field("thumbnail", "upload", uploadfoder='uploads')
)
from smarthumb import SMARTHUMB
Article.thumbnail.compute = lambda row: SMARTHUMB(row.picture, (200,200))
#controllers\default.py
def addarticle():
form = SQLFORM(Article).process()
return dict(form=form)
def showarticle():
id = request.args(0) or redirect(URL('default', 'index'))
article = Article[id]
return dict(article=article)
#views\addarticle.html
<h1> Add an article </1>
{{=form}}
#views\showarticle.html
<article>
<h1> {{=article.title}}</h1>
<div style="width:200px; height:200px; max-width:200px; overflow:hidden;">
<img src="{{=URL('default', 'download', args=article.image)}}" />
</div>
<p>{{=MARKMIN(article.article_text)}}</p>
</article>