python - Django 图片上传和调整大小

标签 python django python-imaging-library image-uploading

我有一个带有图像字段的标准 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/

相关文章:

python - Pyramid 读取http数据

python - pygame程序中未打印字体

python - 如何从 fastapi 响应返回 PIL 图像文件列表?

python - 如何跟踪有多少外键连接到一个对象?

python - 如何将从元组列表创建的 png 图像转换回该元组列表?

python - 将 2D Numpy 灰度值数组转换为 PIL 图像

python - Flask:Config.py - 如何将开发与生产分开?

python - 使用 OpenCV 删除部分图像

mysql - Yosemite 上的 MySQL 问题

python - 解析字符串 - python 中的正则表达式帮助