clean html and correct img ratios

 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
65
66
67
68
import os
import re
from PIL import Image
from django.conf import settings

number_re = re.compile(r'^\d+$')

def clean_html(html, max_width=None, max_height=None):
    try:
        from BeautifulSoup import BeautifulSoup as Soup
    except ImportError:
        return html
    from django.conf import settings
    soup = Soup(html)
    images = soup.findAll('img', src=re.compile(r'^%s.+' % settings.MEDIA_URL),
            width=number_re, height=number_re)
    for image in images:
        rel_path = image['src'].replace(settings.MEDIA_URL, '')
        path = os.path.join(settings.MEDIA_ROOT, rel_path)
        try:
            im = Image.open(path)
        except IOError:
            pass
        else:
            xr, yr = float(image['width']), float(image['height'])
            if max_width is not None and xr > max_width:
                xr = max_width
            if max_height is not None and yr > max_height:
                xy = max_height
            x, y = [float(v) for v in im.size]
            r = min(1.0, min(xr/x, yr/y))
            image['width'] = int(round(x*r, 0))
            image['height'] = int(round(y*r, 0))
    return unicode(soup)



#
# template filter code...
#
import re
from django import template
from django.conf import settings

register = template.Library()

number_re = re.compile(r'^\d+$')

@register.filter
def resize_images(html):
    try:
        from BeautifulSoup import BeautifulSoup as Soup
        from sorl.thumbnail.main import DjangoThumbnail
    except ImportError:
        return html
    soup = Soup(html)
    images = soup.findAll('img', src=re.compile(r'^%s.+' % settings.MEDIA_URL),
            width=number_re, height=number_re)
    for image in images:
        rel_path = image['src'].replace(settings.MEDIA_URL, '')
        requested_size = (int(image['width']), int(image['height']))
        try:
            thumb = DjangoThumbnail(rel_path, requested_size)
        except:
            pass
        else:
            image['src'] = thumb.absolute_url
    return unicode(soup)

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.