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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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().
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0