尝试使用PIL压缩图像时的KeyError

时间:2018-03-11 23:23:32

标签: python django python-imaging-library

我尝试使用PIL压缩上传的图片,以便更快地上传。以下是我的观点:

print(instance.image) #prints "imagename.jpg"
instance.image = Image.open(instance.image)
print(instance.image) #prints "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3190x2159 at 0x10EE73A20>"
instance.image.thumbnail((220, 130), Image.ANTIALIAS)
print(instance.image) #prints "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=193x130 at 0x10EE73A20>"
instance.image.save(instance.image, quality=60)

最后一行引发错误。

Traceback:

File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/Users/zorgan/Desktop/project/site/post/views.py" in post
  55.                 instance.image.save(instance.image, quality=60)

File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/PIL/Image.py" in save
  1713.             format = EXTENSION[ext]

Exception Type: KeyError at /post/
Exception Value: ''

知道问题是什么吗?

编辑:以下代码:

...
if form_post.is_valid():
    instance = form_post.save(commit=False)
    instance.user = request.user

if instance.image:
    filename = instance.image
    instance.image = Image.open(instance.image)
    instance.image.thumbnail((220, 130), Image.ANTIALIAS)
    instance.image.save(filename, quality=60)

instance.save()

在最后一行('JpegImageFile' object has no attribute '_committed'

上返回instance.save()错误

0 个答案:

没有答案