images.py 1.53 KB
Newer Older
kaiyou's avatar
kaiyou committed
1
from tedimg import app
Yoann Ono Dit Biot's avatar
Yoann Ono Dit Biot committed
2
from PIL import Image, ImageSequence
kaiyou's avatar
kaiyou committed
3

kaiyou's avatar
kaiyou committed
4
5
import os
import binascii
kaiyou's avatar
kaiyou committed
6
7
import requests
import io
8
import urllib
kaiyou's avatar
kaiyou committed
9
10


kaiyou's avatar
kaiyou committed
11
def get_image(root, name):
kaiyou's avatar
kaiyou committed
12
13
    """ Try and get basic image attributes.
    """
14
    filename = urllib.parse.quote(os.path.basename(name))
15
16
    return (os.path.join(root, app.config["FULL_WEB"], filename),
            os.path.join(root, app.config["THUMB_WEB"], filename))
kaiyou's avatar
kaiyou committed
17
18
19
20
21
22
23
24
25
26
27
28


def image_from_file(file_storage):
    """ Try and read the uploaded file.
    """
    image = Image.open(file_storage)
    return image


def image_from_url(url):
    """ Try and download an image from the given url.
    """
kaiyou's avatar
kaiyou committed
29
30
31
    response = requests.get(url)
    image = Image.open(io.BytesIO(response.content))
    return image
kaiyou's avatar
kaiyou committed
32
33
34
35
36


def save_with_thumbnail(image, filename):
    dest = "."
    while os.path.exists(os.path.join(app.config["FULL_STORAGE"], dest)):
37
38
        filename, _ = os.path.splitext(filename)
        ext = image.format.lower()
kaiyou's avatar
kaiyou committed
39
        random = binascii.hexlify(os.urandom(3)).decode('utf8')
40
        dest = "%s-%s.%s" % (filename, random, ext)
kaiyou's avatar
kaiyou committed
41
42
43
    # Grab some configuration
    full_file = os.path.join(app.config["FULL_STORAGE"], dest)
    thumb_file = os.path.join(app.config["THUMB_STORAGE"], dest)
kaiyou's avatar
kaiyou committed
44
    thumb_size = app.config["THUMB_SIZE"]
kaiyou's avatar
kaiyou committed
45
    # Save the image and thumbnail
Yoann Ono Dit Biot's avatar
Yoann Ono Dit Biot committed
46
47
48
49
    if image.format == 'GIF':
        image.save(full_file, format=image.format, save_all=True)
    else:
        image.save(full_file, format=image.format)
kaiyou's avatar
kaiyou committed
50
    image.thumbnail((thumb_size, thumb_size))
kaiyou's avatar
kaiyou committed
51
    image.save(thumb_file, format=image.format)
kaiyou's avatar
kaiyou committed
52
    return dest