Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What size to specify to `PIL.Image.frombytes`

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?

like image 360
Ram Rachum Avatar asked Jul 28 '14 13:07

Ram Rachum


People also ask

What is PIL format image?

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.

How do I make an image PIL?

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

How do I find the size of an image in Python?

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.


2 Answers

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)
like image 188
Fred Foo Avatar answered Oct 17 '22 06:10

Fred Foo


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))
like image 36
Jan Spurny Avatar answered Oct 17 '22 08:10

Jan Spurny