繁体   English   中英

如何将 pil 裁剪图像保存到 django 中的图像字段

[英]how to save pil cropped image to image field in django

我正在尝试将裁剪后的图像保存到模型中。 我收到以下错误:

回溯(最近一次调用):文件“/mypath/lib/python2.7/site-packages/django/core/handlers/base.py”,第 132 行,在 get_response 响应=wrapped_callback(request, *callback_args, ** callback_kwargs) 文件“/mypath/lib/python2.7/site-packages/django/contrib/auth/decorators.py”,第 22 行,在 _wrapped_view 中返回 view_func(request, *args, **kwargs) 文件“/mypath/ views.py”,第 236 行,在 player_edit player.save() 文件“/mypath/lib/python2.7/site-packages/django/db/models/base.py”,第 734 行,保存 force_update=force_update, update_fields=update_fields) 文件 "/mypath/lib/python2.7/site-packages/django/db/models/base.py", line 762, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using , update_fields) 文件“/mypath/lib/python2.7/site-packages/django/db/models/base.py”,第 824 行,在 _save_table for f in non_pks] 文件“/mypath/lib/python2.7/ site-packages/django/db/models/fields/files.py", line 313, in pre_save if file and not file._ 已提交:文件“/mypath/lib/python2.7/site-packages/PIL/Image.py”,第 512 行,在getattr 中引发 AttributeError(name) AttributeError: _committed

我处理表单提交的视图如下所示:

if request.method == 'POST':
        form = PlayerForm(request.POST, request.FILES, instance=current_player)
        if form.is_valid():

            temp_image = form.cleaned_data['profile_image2']
            player = form.save()
            cropped_image = cropper(temp_image, crop_coords)
            player.profile_image = cropped_image
            player.save() 
            return redirect('player')

裁剪功能如下所示:

from PIL import Image
import Image as pil

    def cropper(original_image, crop_coords):

        original_image = Image.open(original_image)

        original_image.crop((0, 0, 165, 165))

        original_image.save("img5.jpg")

        return original_image

这是将裁剪后的图像保存到模型的正确过程吗? 如果是这样,为什么我会收到上述错误?

谢谢!

该函数应如下所示:

# The crop function looks like this:

from PIL import Image

from django.core.files.base import ContentFile

def cropper(original_image, crop_coords):
      img_io = StringIO.StringIO()
      original_image = Image.open(original_image)
      cropped_img = original_image.crop((0, 0, 165, 165))
      cropped_img.save(img_io, format='JPEG', quality=100)
      img_content = ContentFile(img_io.getvalue(), 'img5.jpg')
      return img_content

对于 Python 版本 >= 3.5

from io import BytesIO, StringIO()

img_io = StringIO() # or use BytesIO() depending on the type

其余的事情与@phourxx 的回答很好用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM