utils.py 918 Bytes
Newer Older
1
2
3
4
# Image utils

from io import BytesIO
from PIL import Image
Skia's avatar
Skia committed
5
6
7
# from exceptions import IOError
import PIL
from django.core.files.base import ContentFile
8
9
10
11
12
13
14
15
16
17
18
19

def scale_dimension(width, height, long_edge):
    if width > height:
        ratio = long_edge * 1. / width
    else:
        ratio = long_edge * 1. / height
    return int(width * ratio), int(height * ratio)

def resize_image(im, edge, format): # TODO move that into a utils file
    (w, h) = im.size
    (width, height) = scale_dimension(w, h, long_edge=edge)
    content = BytesIO()
Skia's avatar
Skia committed
20
21
22
23
24
25
    im = im.resize((width, height), PIL.Image.ANTIALIAS)
    try:
        im.save(fp=content, format=format.upper(), quality=90, optimize=True, progressive=True)
    except IOError:
        PIL.ImageFile.MAXBLOCK = im.size[0] * im.size[1]
        im.save(fp=content, format=format.upper(), quality=90, optimize=True, progressive=True)
26
27
    return ContentFile(content.getvalue())