本文介绍了PIL open()方法不适用于BytesIO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于某些原因,当我尝试从BytesIO流制作图像时,它无法识别该图像.这是我的代码:
For some reason, when I try to make an image from a BytesIO steam, it can't identify the image. Here is my code:
from PIL import Image, ImageGrab
from io import BytesIO
i = ImageGrab.grab()
i.resize((1280, 720))
output = BytesIO()
i.save(output, format = "JPEG")
output.flush()
print(isinstance(Image.open(output), Image.Image))
及其引发的错误的堆栈跟踪:
And the stack trace of the error it throws:
Traceback (most recent call last):
File "C:/Users/Natecat/PycharmProjects/Python/test.py", line 9, in <module>
print(isinstance(Image.open(output), Image.Image))
File "C:\Python27\lib\site-packages\PIL\Image.py", line 2126, in open
% (filename if filename else fp))
IOError: cannot identify image file <_io.BytesIO object at 0x02394DB0>
我正在使用PIL的Pillow实现.
I am using the Pillow implementation of PIL.
推荐答案
将BytesIO视为文件对象,完成写入图像后,文件的光标位于文件的末尾,因此当Image.open()
尝试执行以下操作时:调用output.read()
,它会立即获得EOF.
Think of BytesIO as a file object, after you finish writing the image, the file's cursor is at the end of the file, so when Image.open()
tries to call output.read()
, it immediately gets an EOF.
在将output
传递到Image.open()
之前,您需要添加output.seek(0)
.
You need to add a output.seek(0)
before passing output
to Image.open()
.
这篇关于PIL open()方法不适用于BytesIO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!