我正在尝试将裁剪的图像保存到模型中。我收到以下错误:
Traceback(最近一次调用最后一次):文件 “/mypath/lib/python2.7/site-packages/django/core/handlers/base.py” 第132行,在get_response response = wrapped_callback(请求, * 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()文件中 “/mathath/lib/python2.7/site-packages/django/db/models/base.py”,行 734,在save force_update = force_update中, update_fields = update_fields)文件 “/mathath/lib/python2.7/site-packages/django/db/models/base.py”,行 762,在save_base中更新= self._save_table(raw,cls, force_insert,force_update,using,update_fields)文件 “/mathath/lib/python2.7/site-packages/django/db/models/base.py”,行 824,在_save_table中为non_pks中的f]文件 “/mypath/lib/python2.7/site-packages/django/db/models/fields/files.py” 第313行,在pre_save中,如果是file而不是file._committed: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
将裁剪后的图像保存到模型是否正确?如果是这样,为什么我会收到上述错误?
谢谢!
答案 0 :(得分:4)
该功能应如下所示:
# 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
答案 1 :(得分:1)
对于Python版本> = 3.5
from io import BytesIO, StringIO()
img_io = StringIO() # or use BytesIO() depending on the type
通过@phourxx答案,其余的工作都很好