utils.py 1.29 KB
Newer Older
1 2 3
# Image utils

from io import BytesIO
Skia's avatar
Skia committed
4
from PIL import Image, ExifTags
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

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)

Skia's avatar
Skia committed
16
def resize_image(im, edge, format):
17 18 19
    (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())

Skia's avatar
Skia committed
28 29 30 31 32 33 34 35 36 37 38 39 40
def exif_auto_rotate(image):
    for orientation in ExifTags.TAGS.keys() :
        if ExifTags.TAGS[orientation]=='Orientation' : break
    exif=dict(image._getexif().items())

    if   exif[orientation] == 3 :
        image=image.rotate(180, expand=True)
    elif exif[orientation] == 6 :
        image=image.rotate(270, expand=True)
    elif exif[orientation] == 8 :
        image=image.rotate(90, expand=True)

    return image