不允许图片小于特定尺寸 [英] Not allowing images small than certain dimensions

查看:112
本文介绍了不允许图片小于特定尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存用户个人资料图像的模型。如果上传的图片大于200x200像素,则我们将尺寸调整为200x200。如果图片大小正确在200x200,则我们将返回该图片。我现在要向用户抛出一个错误,说该图像太小并且不允许使用。这是我的东西:

I have a model that saves user profile images. If the image that is uploaded is greater than 200x200 pixels, then we resize to 200x200. If the image is right at 200x200, then we return that image. What I want now is to throw an error to the user saying that this image is too small and is not allowed. Here's what I have:

class Profile(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    user    = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    bio     = models.CharField(max_length=200, null=True)
    avatar  = models.ImageField(upload_to="img/path")
    gender  = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)
        if self.avatar:
            image = Image.open(self.avatar)
            height, width = image.size
            if height == 200 and width == 200:
                image.close()
                return

            if height < 200 or width < 200:
                return ValidationError("Image size must be greater than 200")
            image = image.resize((200, 200), Image.ANTIALIAS)
            image.save(self.avatar.path)
            image.close()

当图像的宽度小于200px时或高度,请勿上传图片。但是,正在上传图像。我该如何阻止这种情况的发生?

When an image is smaller than 200px in width or height, the image should not be uploaded. However, the image is being uploaded. How can I stop this from happening?

推荐答案

而不是在 save()方法,您可以采用以下形式:

Instead of doing that in save() method, you can do it in forms:

from django.core.files.images import get_image_dimensions
from django import forms

class ProfileForm(forms.ModelForm):
   class Meta:
       model = Profile

   def clean_avatar(self):
       picture = self.cleaned_data.get("avatar")
       if not picture:
           raise forms.ValidationError("No image!")
       else:
           w, h = get_image_dimensions(picture)
           if w < 200:
               raise forms.ValidationError("The image is %i pixel wide. It's supposed to be more than 200px" % w)
           if h < 200:
               raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
       return picture

之所以这样做是因为,当您调用 save()时,图像已经上传。因此最好以表格形式进行。

Reason for this is because, when you have called save(), image is already uploaded. So its better to do it in forms.

这篇关于不允许图片小于特定尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆