A filter to resize a ImageField on demand, a use case could be:
<img src="{{ object.image.url }}" alt="original image">
<img src="{{ object.image|thumbnail }}" alt="image resized to default 104x104 format">
<img src="{{ object.image|thumbnail:200x300 }}" alt="image resized to 200x300">
Original http://www.djangosnippets.org/snippets/192/
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 | import os
import Image
from django.template import Library
register = Library()
def thumbnail(file, size='104x104'):
# defining the size
x, y = [int(x) for x in size.split('x')]
# defining the filename and the miniature filename
filehead, filetail = os.path.split(file.path)
basename, format = os.path.splitext(filetail)
miniature = basename + '_' + size + format
filename = file.path
miniature_filename = os.path.join(filehead, miniature)
filehead, filetail = os.path.split(file.url)
miniature_url = filehead + '/' + miniature
if os.path.exists(miniature_filename) and os.path.getmtime(filename)>os.path.getmtime(miniature_filename):
os.unlink(miniature_filename)
# if the image wasn't already resized, resize it
if not os.path.exists(miniature_filename):
image = Image.open(filename)
image.thumbnail([x, y], Image.ANTIALIAS)
try:
image.save(miniature_filename, image.format, quality=90, optimize=1)
except:
image.save(miniature_filename, image.format, quality=90)
return miniature_url
register.filter(thumbnail)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
para o ultimo exemplo funcionar tem que fazer assim: {{ object.image|thumbnail:"200x300" }}
#
Awesome tag! Works perfectly!
#
Doesn't work with gof images :S
#
If you are using Umlauts or other weird letters (utf-8) in your filenames you will have to take care of this.
Replace
with
#
Please login first before commenting.