Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

python - PIL open() method not working with 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:Python27libsite-packagesPILImage.py", line 2126, in open
    % (filename if filename else fp))
IOError: cannot identify image file <_io.BytesIO object at 0x02394DB0>

I am using the Pillow implementation of PIL.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

You need to add a output.seek(0) before passing output to Image.open().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...