Commit 4ffef2f2 authored by fred's avatar fred
Browse files

add a filter tag to resize images

example usage: <img src="{{ episode.image|thumbnail:'50x50' }}" />
parent 74944206
# initiated from http://djangosnippets.org/snippets/2145/
import os
import re
from PIL import Image
from django.db.models.signals import post_save, pre_delete
from django.template import Library
register = Library()
def thumbnail(image, size='100x100'):
# 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(image.path)
basename, format = os.path.splitext(filetail)
miniature = basename + '_' + size + format
filename = image.path
miniature_filename = os.path.join(filehead, miniature)
filehead, filetail = os.path.split(image.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)
if abs( (1.0*x/y) - (1.0*image.size[0]/image.size[1]) ) > 0.1:
# aspect ratio change, crop the image first
if image.size[0] > image.size[1]: # landscape
box = [0, 0, int(image.size[1] * (1.0*x/y)), image.size[1]]
box[0] = (image.size[0] - box[2]) / 2 # keep the middle
else:
box = [0, 0, image.size[0], int(image.size[0] * (1.0*x/y))]
box[1] = (image.size[1] - box[3]) / 4 # keep mostly the top
image = image.crop(box)
image = image.resize([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)
def clean_thumb(sender, instance, **kwargs):
if not hasattr(instance, 'image'):
return
name, ext = os.path.splitext(os.path.basename(instance.image.name))
exp = '^%s_\d+x\d+x[0-1]{1}\%s' % (name, ext)
for file_path in os.listdir(settings.MEDIA_ROOT):
if re.search(exp, file_path):
os.unlink(settings.MEDIA_ROOT + file_path)
post_save.connect(clean_thumb)
pre_delete.connect(clean_thumb)
{% load thumbnails %}
<!--
<li>{{ episode.first_diffusion|date:"d E o H:i"|lower }}
......@@ -26,7 +27,11 @@
<button class="symbol play">A</button><button class="symbol add">B</button>
</div>
<div class="logo right">
{% if episode.image %}
<img width="50" height="50" src="{{ episode.image|thumbnail:'50x50' }}"/>
{% else %}
<img src="http://placehold.it/50X50" />
{% endif %}
</div>
<div class="content">
<h5 class="title ellipsis"><a href="{{ episode.slug }}">{{ episode.title }}</a></h5>
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment