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?
Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux. The latest version of PIL is 1.1.
new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band).
open() is used to open the image and then . width and . height property of Image are used to get the height and width of the image.
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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With