簡體   English   中英

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

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

我試圖用Python(v2.7.2)和Pillow(v2.4.0)生成100x100的全黑圖像,但結果卻很奇怪。

這是我的代碼

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

這是我的結果(放大后請忽略灰色邊框-它來自OS X預覽版)。 圖像應為黑色,但不是。

我究竟做錯了什么?

由枕頭生成的圖像;出了點問題

bytes([0] * 10)是字符串"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" 因此,像素的顏色是'[''0'','' '']'符號的ASCII碼。

要獲取零字節的字節字符串,請使用bytes("\\x00" * 100 * 100) \\x00是十六進制值00的字節。

實際上,您甚至不需要bytes(...)調用。 bytes僅在Python 3.x中是類型。 在Python中,2.7.x bytes只是str的別名。

因此,最終代碼應為:

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