简体   繁体   English

使用Pillow(PIL)在Python中生成图像

[英]Generating image in Python using Pillow (PIL)

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. 我试图用Python(v2.7.2)和Pillow(v2.4.0)生成100x100的全黑图像,但结果却很奇怪。

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). 这是我的结果(放大后请忽略灰色边框-它来自OS X预览版)。 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]" . bytes([0] * 10)是字符串"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" So, the colors of your pixels are the ASCII codes of '[' , '0' , ',' , ' ' , and ']' symbols. 因此,像素的颜色是'[''0'','' '']'符号的ASCII码。

To get the byte string of zero bytes use bytes("\\x00" * 100 * 100) instead. 要获取零字节的字节字符串,请使用bytes("\\x00" * 100 * 100) Here \\x00 is the byte with hexadecimal value 00 . \\x00是十六进制值00的字节。

Actually you don't even need bytes(...) call. 实际上,您甚至不需要bytes(...)调用。 bytes is the type only in Python 3.x. bytes仅在Python 3.x中是类型。 In Python 2.7.x bytes is just an alias for str . 在Python中,2.7.x bytes只是str的别名。

So, the final code should be: 因此,最终代码应为:

from PIL import Image
im = Image.frombytes('L', (100, 100), "\x00" * 100 * 100)
im.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM