Python3 Django1.9 PIL 涉及使用 io.BytesIO 保存图像文件的问题 - 在终端中有效,但在服务器中无效

Meg*_*Ray 1 python django python-imaging-library python-3.x

Python:3.4.3
Django:1.9.7
异常类型:TypeError
异常值:“_io._IOBase”对象的描述符“fileno”需要参数
异常位置:/usr/lib/python3/dist-packages/PIL/ImageFile.py在 _save,第 454 行

这是我在终端中测试过的代码 -

 import urllib.request
 from PIL import Image
 from io import BytesIO

 url = 'http://s.inyourpocket.com/gallery/108367.jpg'
 i = Image.open(BytesIO(urllib.request.urlopen(url).read()))
 img_file = BytesIO()
 i.save(img_file, 'JPEG')
Run Code Online (Sandbox Code Playgroud)

该代码在终端中运行得很好,但是一旦在 Django 服务器上进行测试,它就会给我这些错误 -

File "PATH/utils.py", line 124, in pil_to_django
  image.save(img_file, 'JPEG')
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1468, in save
  save_handler(self, fp, filename)
File "/usr/lib/python3/dist-packages/PIL/JpegImagePlugin.py", line 579, in _save
  ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)], bufsize)
File "/usr/lib/python3/dist-packages/PIL/ImageFile.py", line 454, in _save
  fh = fp.fileno()
TypeError: descriptor 'fileno' of '_io._IOBase' object needs an argument
Run Code Online (Sandbox Code Playgroud)

服务器中运行的代码是utils.pyviews.py-

# utils.py
def pil_to_django(image, format="JPEG"):
    img_file = io.BytesIO
    image.save(img_file, 'JPEG')
    return ContentFile(img_file.getvalue())
Run Code Online (Sandbox Code Playgroud)


# views.py
pil_image = Image.open(BytesIO(urllib.request.urlopen(url).read()))
django_file = pil_to_django(pil_image)
Run Code Online (Sandbox Code Playgroud)

kav*_*veh 6

您忘记实例化BytesIO类。改成img_file = io.BytesIOimg_file = io.BytesIO()