Generating image in Python using Pillow (PIL)

丶灬走出姿态 提交于 2019-12-06 03:36:16

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/22956857/generating-image-in-python-using-pillow-pil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!