Reputation: 88578
I'd like to create a PIL image from raw data. I believe I'm supposed to use PIL.Image.frombytes
. But it has a size
argument. I don't know the size of the image, isn't that supposed to come as part of the image? I don't know the size of the image in advance. How am I supposed to call the function with no size?
Upvotes: 18
Views: 23992
Reputation: 3356
thanks to @jan-spurny for giving the clue. for anyone else who needs to open an image from bytes
from PIL import Image
import io
image_bytes = ...
im = Image.open(io.BytesIO(image_bytes))
Upvotes: 9
Reputation: 5527
Since you clarified, that you don't want to read raw pixel data, but rather in-memory image file, the solution is clear: don't use frombytes
- it is meant for raw pixel data. Use just open from StringIO
:
image = Image.open(StringIO.StringIO(image_data))
Upvotes: 20
Reputation: 363597
The size
argument must match the image dimensions, which are not encoded in a raw pixel buffer (e.g. a buffer of length n can represent any grid of k×m pixels for k, m > 0, k×m = n). You have to know this size in advance.
Some example code to demonstrate both tobytes
and frombytes
:
>>> img = PIL.Image.open("some_image.png")
>>> img.size
(482, 295)
>>> raw = img.tobytes()
>>> img2 = PIL.Image.frombytes(img.mode, img.size, raw)
Upvotes: 8