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

Atm*_*tma 7 python django django-models django-views python-imaging-library

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

回溯(最近一次调用):文件“/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", line 824, in _save_table for f in non_pks] File "/mypath/lib/python2.7/site-packages/django /db/models/fields/files.py", line 313, in pre_save if file and not file._committed: File "/mypath/lib/python2.7/site-packages/PIL/Image.py", line 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')
Run Code Online (Sandbox Code Playgroud)

裁剪功能如下所示:

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
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

pho*_*rxx 5

该函数应如下所示:

# 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
Run Code Online (Sandbox Code Playgroud)