An update to snippet 1718 (http://www.djangosnippets.org/snippets/1718/). This update lets you pass an image URL string as well as a model ImageField instance. This means that you can then create thumbnails on demand for images outside of model
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import os
import Image
from django.template import Library
register = Library()
def thumbnail(file, size='200x200'):
"""
Example:
<img src="object.get_image_url" alt="original image" />
<img src="object.image|thumbnail" alt="image resized to default 200x200 format" />
<img src="object.image|thumbnail:"200x300" alt="image resized to 200x300" />
The filter is applied to a image field (not the image url get from
get_image_url method of the model), supposing the image filename is
"image.jpg", it checks if there is a file called "image_200x200.jpg" or
"image_200x300.jpg" on the second case, if the file isn't there, it resizes
the original image, finally it returns the proper url to the resized image.
"""
path = ""
url = ""
if type(file) == str:
path = "%s/%s" % (settings.MEDIA_ROOT, file)
url = "%s%s" % (settings.MEDIA_URL, file)
elif file:
path = file.path
url = file.url
if file:
# defining the size
x, y = [int(x) for x in size.split('x')]
# defining the filename and the miniature filename
basename, format = path.rsplit('.', 1)
baseurl, _format = url.rsplit('.', 1)
miniature_filename = basename + '_' + size + '.' + format
miniature_url = baseurl + '_' + size + '.' + format
# if the image wasn't already resized, resize it
if not os.path.exists(miniature_filename):
image = Image.open(path)
image.thumbnail([x, y])
image.save(miniature_filename, image.format)
print miniature_url
return miniature_url
return ''
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, 8 months ago
Comments
Please login first before commenting.