This repository was archived by the owner on Sep 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathimages.py
More file actions
89 lines (68 loc) · 2.36 KB
/
images.py
File metadata and controls
89 lines (68 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# -*- coding: utf-8 -*-
import base64
import os
from io import BytesIO
import requests
from thumbnails.conf import settings
from thumbnails.helpers import get_engine, get_storage_backend
def extension_of_format(_format):
if _format == "JPEG" or _format == "JPG":
return "jpg"
return _format.lower()
class Thumbnail(object):
size = None, None
image = None
_url = None
extension = None
def __init__(self, name, _format):
self.name = '/'.join(name)
self.extension = extension_of_format(_format)
@property
def path(self):
return os.path.join(settings.THUMBNAIL_PATH, '{}.{}'.format(self.name, self.extension))
@property
def url(self):
if self._url:
return self._url
return '/'.join([settings.THUMBNAIL_URL, '{}.{}'.format(self.name, self.extension)]) \
.replace('//', '/')
@property
def width(self):
return self.size[0]
@property
def height(self):
return self.size[1]
@property
def ratio(self):
return float(self.width) / float(self.height)
@property
def is_portrait(self):
return self.ratio < 1
@property
def is_landscape(self):
return self.ratio > 1
@property
def exists(self):
return get_storage_backend().exists(self.path)
def save(self, options):
return get_storage_backend().save(self.path, get_engine().raw_data(self.image, options))
def alternative_resolution_path(self, resolution):
return os.path.join(
settings.THUMBNAIL_PATH,
'{}@{}x.{}'.format(self.name, resolution, self.extension)
)
def save_alternative_resolution(self, resolution, image, options):
path = self.alternative_resolution_path(resolution)
return get_storage_backend().save(path, get_engine().raw_data(image, options))
class SourceFile(object):
def __init__(self, source_file):
if hasattr(source_file, 'name'):
self.file = source_file.name
else:
self.file = source_file
def open(self):
if self.file.startswith('http'):
return requests.get(self.file, stream=True).raw
elif self.file.startswith(r'data:image/'):
return BytesIO(base64.b64decode(self.file.replace('data:image/jpeg;base64,', '')))
return get_storage_backend().open(self.file)