DataURIConverter   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 42
rs 10
c 0
b 0
f 0
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __call__() 0 12 4
A resize_and_convert() 0 7 1
A is_py3() 0 2 1
A __init__() 0 3 1
A _encode() 0 6 2
A is_url() 0 2 1
A check_pillow_installed() 0 3 2
1
import base64
2
import io
3
import os
4
import sys
5
6
import requests
7
8
from six.moves.urllib.parse import urlparse
9
10
try:
11
    from PIL import Image
12
except ImportError:
13
    Image = None
14
15
from ...errors import PillowNotInstalled
16
17
THUMB_SIZE = (340, 210)
18
19
20
class DataURIConverter(object):
21
    def __init__(self, location):
22
        self.check_pillow_installed()
23
        self.location = location
24
25
    def check_pillow_installed(self):
26
        if Image is None:
27
            raise PillowNotInstalled()
28
29
    def __call__(self):
30
        if os.path.exists(self.location):
31
            with open(self.location, "rb") as fp:
32
                return self._encode(self.resize_and_convert(fp).read())
33
        elif self.is_url():
34
            content = requests.get(self.location).content
35
            fp = io.BytesIO()
36
            fp.write(content)
37
            fp.seek(0)
38
            return self._encode(self.resize_and_convert(fp).read())
39
        else:
40
            raise IOError("{} not found".format(self.location))
41
42
    def resize_and_convert(self, fp):
43
        im = Image.open(fp)
44
        im.thumbnail(THUMB_SIZE)
45
        out = io.BytesIO()
46
        im.save(out, format='png')
47
        out.seek(0)
48
        return out
49
50
    def is_py3(self):
51
        return sys.version_info[0] == 3
52
53
    def is_url(self):
54
        return self.location is not None and urlparse(self.location).scheme in ['http', 'https']
55
56
    def _encode(self, content):
57
        if self.is_py3():
58
            data64 = base64.b64encode(content).decode("ascii")
59
        else:
60
            data64 = content.encode('base64').replace("\n", "")
61
        return data64
62
63
64
def data_uri_from(location):
65
    return DataURIConverter(location)()
66