您没有指定是否使用 Django 表单来上传图像,我假设是在表单字段中执行验证的。
你可以做的是创建一个子类django.forms.fields.ImageField
扩展 to_python 的功能。
目前Django中进行的文件类型检查to_python
看起来像这样
Image.open(file).verify()
你的子类可能看起来像这样。
class DmitryImageField(ImageField):
def to_python(self, data):
f = super(DmitryImageField, self).to_python(data)
if f is None:
return None
try:
from PIL import Image
except ImportError:
import Image
# We need to get a file object for PIL. We might have a path or we might
# have to read the data into memory.
if hasattr(data, 'temporary_file_path'):
file = data.temporary_file_path()
else:
if hasattr(data, 'read'):
file = BytesIO(data.read())
else:
file = BytesIO(data['content'])
try:
im = Image.open(file)
if im.format not in ('BMP', 'PNG', 'JPEG'):
raise ValidationError("Unsupport image type. Please upload bmp, png or jpeg")
except ImportError:
# Under PyPy, it is possible to import PIL. However, the underlying
# _imaging C module isn't available, so an ImportError will be
# raised. Catch and re-raise.
raise
except Exception: # Python Imaging Library doesn't recognize it as an image
raise ValidationError(self.error_messages['invalid_image'])
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return f
您可能会注意到这是来自的大部分代码ImageField.to_python
并且可能更喜欢只创建 FileField 的子类来使用而不是ImageField
而不是子类化ImageField
并复制其大部分功能。在这种情况下,请确保添加im.verify()
在格式检查之前。
编辑:我应该指出,我还没有测试过这个子类。