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?

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