Python3 Django1.9 PIL 问题涉及使用 io.BytesIO 保存图像文件 - 在终端中工作但在服务器中不工作
Python3 Django1.9 PIL Issue involving Saving Image File with io.BytesIO - Works in Terminal but not in the Server
Python : 3.4.3
姜戈:1.9.7
异常类型:TypeError
异常值:“_io._IOBase”对象的描述符 'fileno' 需要参数
异常位置:/usr/lib/python3/dist-packages/PIL/ImageFile.py in _save, line 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')
该代码在终端中运行良好,但一旦在 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
服务器中的代码运行在utils.py
中,从views.py
调用-
# utils.py
def pil_to_django(image, format="JPEG"):
img_file = io.BytesIO
image.save(img_file, 'JPEG')
return ContentFile(img_file.getvalue())
# views.py
pil_image = Image.open(BytesIO(urllib.request.urlopen(url).read()))
django_file = pil_to_django(pil_image)
您忘记实例化 BytesIO
class。将 img_file = io.BytesIO
更改为 img_file = io.BytesIO()
Python : 3.4.3
姜戈:1.9.7
异常类型:TypeError
异常值:“_io._IOBase”对象的描述符 'fileno' 需要参数
异常位置:/usr/lib/python3/dist-packages/PIL/ImageFile.py in _save, line 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')
该代码在终端中运行良好,但一旦在 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
服务器中的代码运行在utils.py
中,从views.py
调用-
# utils.py
def pil_to_django(image, format="JPEG"):
img_file = io.BytesIO
image.save(img_file, 'JPEG')
return ContentFile(img_file.getvalue())
# views.py
pil_image = Image.open(BytesIO(urllib.request.urlopen(url).read()))
django_file = pil_to_django(pil_image)
您忘记实例化 BytesIO
class。将 img_file = io.BytesIO
更改为 img_file = io.BytesIO()