我有一个带有图像字段的标准 Django 表单。上传图片时,我想确保图片不大于 300 像素 x 300 像素。这是我的代码:
def post(request):
if request.method == 'POST':
instance = Product(posted_by=request.user)
form = ProductModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
new_product = form.save(commit=False)
if 'image' in request.FILES:
img = Image.open(form.cleaned_data['image'])
img.thumbnail((300, 300), Image.ANTIALIAS)
# this doesnt save the contents here...
img.save(new_product.image)
# ..because this prints the original width (2830px in my case)
print new_product.image.width
我面临的问题是,我不清楚如何将Image
类型转换为 ImageField 类型。