Django图像上传并调整大小 [英] Django Image upload and resize

查看:178
本文介绍了Django图像上传并调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有图像字段的标准Django表单。当图像上传时,我想确保图像不大于300像素×300像素。这是我的代码:

  def post(request):
if request.method =='POST':
instance = Product(posted_by = request.user)
form = ProductModelForm(request.POST或None,request.FILES或None)
如果form.is_valid():
new_product = form.save(commit = False)
如果请求中的'image'.FILES:
img = Image.open(form.cleaned_data ['image'])
img.thumbnail((300 ,300),Image.ANTIALIAS)

#这不保存内容...
img.save(new_product.image)

#..因为这打印原始宽度(在我的情况下为2830px)
print new_product.image.width

我面临的问题是,我不清楚我如何将 Image 类型转换为ImageField类型的类型。

解决方案

从文档o n ImageField的保存方法


请注意,content参数应该是django.core.files.File的一个实例,而不是Python的内置文件对象。 / p>

这意味着你需要转换 PIL.Image img )到Python文件对象,然后将Python对象转换为一个 django.core.files.File 对象。这样的东西(我还没有测试这个代码)可能会工作:

  img.thumbnail((300,300),Image。 ANTIALIAS)

#将PIL.Image转换为字符串,然后转换为Django文件
#对象。我们使用ContentFile而不是File,因为
#former可以对字符串进行操作。
from django.core.files.base import ContentFile
djangofile = ContentFile(img.tostring())
new_product.image.save(filename,djangofile)


I have a standard Django form with an image field. When the image is uploaded, I would like to make sure that the image is no larger than 300px by 300px. Here is my code:

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

The problem I am facing is, it is not clear to me how I get the Image type converted to the type that ImageField type.

解决方案

From the documentation on ImageField's save method:

Note that the content argument should be an instance of django.core.files.File, not Python's built-in file object.

This means you would need to convert the PIL.Image (img) to a Python file object, and then convert the Python object to a django.core.files.File object. Something like this (I have not tested this code) might work:

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)

这篇关于Django图像上传并调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆