我正在尝试以表单级别验证图像维度,并在提交的照片不符合图像尺寸1080x1920的要求上向用户显示一条消息。我不想将宽度和高度大小存储在数据库中。我尝试使用ImageField宽度和高度属性。但这是行不通的。
class Adv(models.Model):
image = models.ImageField(upload_to=r'photos/%Y/%m/',
width_field = ?,
height_field = ?,
help_text='Image size: Width=1080 pixel. Height=1920 pixel',
您可以通过两种方式进行
-
模型中的验证
来自django.core.corpeptions导入验证
def validate_image(image): max_height = 1920 max_width = 1080 height = image.file.height width = image.file.width if width > max_width or height > max_height: raise ValidationError("Height or Width is larger than what is allowed") class Photo(models.Model): image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image])
-
以形式清洁
def clean_image(self): image = self.cleaned_data.get('image', False) if image: if image._height > 1920 or image._width > 1080: raise ValidationError("Height or Width is larger than what is allowed") return image else: raise ValidationError("No image found")
我们需要一个图像处理库(例如pi)来检测图像维度,这是正确的解决方案:
# Custom validator to validate the maximum size of images
def maximum_size(width=None, height=None):
from PIL import Image
def validator(image):
img = Image.open(image)
fw, fh = img.size
if fw > width or fh > height:
raise ValidationError(
"Height or Width is larger than what is allowed")
return validator
然后在模型中:
class Photo(models.Model):
image = models.ImageField('Image', upload_to=image_upload_path, validators=[maximum_size(128,128)])