+-
python – Django图像上传和调整大小
我有一个带有图像字段的标准Django表单.上传图片时,我想确保图片不超过300像素×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类型的类型.

最佳答案
从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图像上传和调整大小 - 乐贴网