Answer the question
In order to leave comments, you need to log in
How to work in Django with ImageField check, resize photo?
Let's say there is a gallery with photos, there are a lot of them on the page, >100<200.
What is the best way to implement a miniature copy of a photo with dimensions of approximately 200 * 200, a large copy of 800 * 800 and the original?
How to check photo size before uploading?
Answer the question
In order to leave comments, you need to log in
To work with thumbnails, there are easy-thumbnails , you don't have to reinvent the wheel. And to check the size of the uploaded image, you can define your own field class:
class LimitedImageField(ImageField):
def __init__(self, *args, **kwargs):
self.max_upload_size = kwargs.pop('max_upload_size', None)
self.min_dim = kwargs.pop('min_dim', None)
self.max_dim = kwargs.pop('max_dim', None)
if not self.max_upload_size:
self.max_upload_size = settings.FILE_UPLOAD_MAX_MEMORY_SIZE
super(LimitedImageField, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super(LimitedImageField, self).clean(*args, **kwargs)
try:
img_file = data.file
if img_file.size > self.max_upload_size:
err_msg = 'Размер файла не должен превышать {}'.format(filesizeformat(self.max_upload_size))
raise forms.ValidationError(err_msg)
w, h = get_image_dimensions(img_file)
if self.min_dim:
if (w < self.min_dim[0]) or (h < self.min_dim[1]):
err_msg = 'Разрешение изображения не должно быть меньше, чем {}x{}'.format(*self.min_dim)
raise forms.ValidationError(err_msg)
if self.max_dim:
if (w > self.max_dim[0]) or (h > self.max_dim[1]):
err_msg = 'Разрешение изображения не должно превышать {}x{}'.format(*self.max_dim)
raise forms.ValidationError(err_msg)
except AttributeError:
pass
return data
image = LimitedImageField('Изображение', min_dim=(100, 100), max_dim=(300, 300),
help_text='Разрешение от 100x100 до 300х300')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question