【发布时间】:2017-07-22 06:41:09
【问题描述】:
我有一个 Django 应用程序,它通过包含 POST 和 FILES 值的多部分表单收集数据。我的 Django 视图正确接收了表单数据,我正在尝试处理通过表单传递的图像文件,以便通过 PIL.Image 生成缩略图。但是,当我调用 Image.thumbnail() 方法(或者,就此而言,除 Image.open() 之外的任何方法)时,我得到一个 IOError,我无法进一步调查。
代码如下:
from PIL import Image
import io
import os
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files.base import ContentFile
from django.conf import settings
def generate_thumbnail(file):
if 'image' in file.content_type:
print "about to save the thumbnail"
file_content= ContentFile(file.read())
print "file read"
full_filename = os.path.join(settings.MEDIA_ROOT, file.name)
print "path selected"
fout = open(full_filename, 'wb+')
for chunk in file_content.chunks():
fout.write(chunk)
fout.close()
print " file saved"
im = Image.open(open(full_filename, 'rb'))
print im.getbands()
#no problem up to this point
try:
size = 128,128
thumb = im.thumbnail(size)
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
脚本引发了 IOError 异常,但打印出来的只是“I/O 错误(无):无”。请注意 fout.write() 成功将我的文件写入所选路径,并且 Image.open() 和 Image.getbands() 成功工作(后者正确返回, ('R', 'G', ' B'))。但是任何调用 Image.load() 的东西 - 在这种情况下是 Image.thumbnail() - 似乎都不起作用。
有什么想法吗?
【问题讨论】:
标签: django image python-2.7 thumbnails pillow