Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating image in Python using Pillow (PIL)

Tags:

python

pillow

I'm trying to generate a 100x100 all-black image with Python (v2.7.2) and Pillow (v2.4.0) and I get a very weird result.

This is my code

from PIL import Image
im = Image.frombytes('L', (100, 100), bytes([0] * 100 * 100))
im.show()

This is my result (zoomed-in and please ignore the grey border - it comes from OS X Preview). The image should be black, but it is not.

What am I doing wrong?

Image generated by Pillow; something's wrong

like image 468
The Gruffalo Avatar asked Apr 09 '14 08:04

The Gruffalo


1 Answers

The result of bytes([0] * 10) is the string "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]". So, the colors of your pixels are the ASCII codes of '[', '0', ',', ' ', and ']' symbols.

To get the byte string of zero bytes use bytes("\x00" * 100 * 100) instead. Here \x00 is the byte with hexadecimal value 00.

Actually you don't even need bytes(...) call. bytes is the type only in Python 3.x. In Python 2.7.x bytes is just an alias for str.

So, the final code should be:

from PIL import Image
im = Image.frombytes('L', (100, 100), "\x00" * 100 * 100)
im.show()
like image 51
citxx Avatar answered Oct 16 '22 00:10

citxx