Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:\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>

I am using the Pillow implementation of PIL.

like image 351
Natecat Avatar asked May 10 '14 23:05

Natecat


People also ask

Is BytesIO file like?

StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.

What does PIL image Open return?

Steps to Read an Image using PIL open() method and pass the path to image file as argument. Image. open() returns an Image object. You can store this image object and apply image operations on it.

What is PIL image Fromarray?

Returns: An Image object. PIL.Image. fromarray(obj, mode=None)[source] Creates an image memory from an object exporting the array interface (using the buffer protocol).


1 Answers

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().

like image 53
Lie Ryan Avatar answered Oct 25 '22 21:10

Lie Ryan