Completed
Push — master ( 84e615...a5de1a )
by Johannes
01:08
created

MinSizeValidator   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 10
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 1
c 5
b 0
f 0
dl 0
loc 10
rs 10

1 Method

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