Total Complexity | 12 |
Total Lines | 42 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import base64 |
||
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 | |||
66 |