[UPDATE]Filter to resize a ImageField on demand + RATIO OPTION + CLEANUP

 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
52
53
54
55
56
57
58
59
60
61
62
63
64
import os
import os.path
import re
import Image
from django.template import Library

register = Library()

def thumbnail(file, size='100x100x1'):
    # defining the size
    x, y, ratio = [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)
        if ratio == 0:
            image = image.resize([x, y], Image.ANTIALIAS)
        else:
            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)



# CLEAN CODE (CHANGE THE VARIABLES)

from os import listdir, remove
from os.path import basename, splitext
from re import search

from django.db.models.signals import post_save, pre_delete

from eduardomillan import settings


    

def clean_thumb(sender, instance, **kwargs):
    name, ext = splitext(basename(instance.IMAGE_FIELD.name))
    exp = '^%s_\d+x\d+x[0-1]{1}\%s' % (name, ext)
    for file_path in listdir(settings.MEDIA_ROOT):
        if search(exp, file_path):
            remove(settings.MEDIA_ROOT + file_path)



post_save.connect(clean_thumb, sender=FIELD_MODEL)
pre_delete.connect(clean_thumb, sender=FIELD_MODEL)

More like this

  1. [UPDATE]Filter to resize a ImageField on demand by rafacdb 4 years, 9 months ago
  2. Filter to resize a ImageField on demand by michelts 6 years, 1 month ago
  3. ResizeImageField by wim 2 years, 7 months ago
  4. Sharpening images by rajeshd 6 years, 2 months ago
  5. Unsharp Mask with PIL and PythonMagick by VidJa 4 years, 4 months ago

Comments

(Forgotten your password?)