|
1
|
|
|
from io import BytesIO |
|
2
|
|
|
|
|
3
|
|
|
from django.core.exceptions import ValidationError |
|
4
|
|
|
from django.core.validators import BaseValidator |
|
5
|
|
|
from django.utils.translation import ugettext_lazy as _ |
|
6
|
|
|
from PIL import Image |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
class BaseSizeValidator(BaseValidator): |
|
10
|
|
|
"""Base validator that validates the size of an image.""" |
|
11
|
|
|
|
|
12
|
|
|
def compare(self, x): |
|
13
|
|
|
return True |
|
14
|
|
|
|
|
15
|
|
|
def __init__(self, width, height): |
|
16
|
|
|
self.limit_value = width, height |
|
17
|
|
|
|
|
18
|
|
|
def __call__(self, value): |
|
19
|
|
|
cleaned = self.clean(value) |
|
20
|
|
|
if self.compare(cleaned, self.limit_value): |
|
21
|
|
|
params = { |
|
22
|
|
|
'width': self.limit_value[0], |
|
23
|
|
|
'height': self.limit_value[1], |
|
24
|
|
|
} |
|
25
|
|
|
raise ValidationError(self.message, code=self.code, params=params) |
|
26
|
|
|
|
|
27
|
|
|
@staticmethod |
|
28
|
|
|
def clean(value): |
|
29
|
|
|
value.seek(0) |
|
30
|
|
|
stream = BytesIO(value.read()) |
|
31
|
|
|
img = Image.open(stream) |
|
32
|
|
|
return img.size |
|
33
|
|
|
|
|
34
|
|
|
|
|
35
|
|
|
class MaxSizeValidator(BaseSizeValidator): |
|
36
|
|
|
""" |
|
37
|
|
|
ImageField validator to validate the max width and height of an image. |
|
38
|
|
|
|
|
39
|
|
|
You may use float("inf") as an infinite boundary. |
|
40
|
|
|
""" |
|
41
|
|
|
|
|
42
|
|
|
def compare(self, img_size, max_size): |
|
43
|
|
|
return img_size[0] > max_size[0] or img_size[1] > max_size[1] |
|
44
|
|
|
message = _('The image you uploaded is too large.' |
|
45
|
|
|
' The required maximum resolution is:' |
|
46
|
|
|
' %(width)sx%(height)s px.') |
|
47
|
|
|
code = 'max_resolution' |
|
48
|
|
|
|
|
49
|
|
|
|
|
50
|
|
|
class MinSizeValidator(BaseSizeValidator): |
|
51
|
|
|
""" |
|
52
|
|
|
ImageField validator to validate the min width and height of an image. |
|
53
|
|
|
|
|
54
|
|
|
You may use float("inf") as an infinite boundary. |
|
55
|
|
|
""" |
|
56
|
|
|
|
|
57
|
|
|
def compare(self, img_size, min_size): |
|
58
|
|
|
return img_size[0] < min_size[0] or img_size[1] < min_size[1] |
|
59
|
|
|
message = _('The image you uploaded is too small.' |
|
60
|
|
|
' The required minimum resolution is:' |
|
61
|
|
|
' %(width)sx%(height)s px.') |
|
62
|
|
|
|