我有一个带有图像字段的标准 Django 表单。上传图片时,我想确保图片不大于 300px x 300px。这是我的代码:
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 类型的类型。
最佳答案
来自 ImageField 的文档 save method :
Note that the content argument should be an instance of django.core.files.File, not Python's built-in file object.
这意味着您需要将 PIL.Image
(img
) 转换为 Python 文件对象,然后将 Python 对象转换为 django。 core.files.File
对象。像这样的东西(我没有测试过这段代码)可能会起作用:
img.thumbnail((300, 300), Image.ANTIALIAS)
# Convert PIL.Image to a string, and then to a Django file
# object. We use ContentFile instead of File because the
# former can operate on strings.
from django.core.files.base import ContentFile
djangofile = ContentFile(img.tostring())
new_product.image.save(filename, djangofile)
关于python - Django 图片上传和调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020717/