Pillow / PIL Python - 只有第一行写入图像

时间:2017-08-02 18:31:20

标签: python python-3.x python-imaging-library pillow

我正在尝试创建一个随机生成游戏地图的Perlin噪音应用程序。我正在尝试写入新图像,但只写入第一行。

这是我创建的存根,它表现出同样的问题:

from PIL import Image
from random import randint

height = 25
width = 25

z = randint(-1000, 1000) / 100

img = Image.new('RGBA', (width, height), color=(255, 255, 255, 255))

for y in range(height):
    img.putdata([(0,255,0,255) for x in range(width)]) # Logic error occurs on this line
img.save("location.png", "PNG")

我这次犯了什么愚蠢的错误?

2 个答案:

答案 0 :(得分:0)

嗯,你需要一个填满整个图像的序列。每次调用时putdata都从0,0开始,所以每次只是从0,0写到序列的末尾。通过这样的方式获得足够长的序列来填充整个图像:

height = 25
width = 25
data = [255 * randint(-1000, 1000) / 100 for x in range(width * height)]

然后你可以像这样使用putdata:

img = Image.new('RGBA', (width, height), color=(255, 255, 255, 255))
img.putdata(data)
img.save("location.png", "PNG")

答案 1 :(得分:0)

您必须按以下方式提供像素信息:

img.putdata([(0,255,0, 255) for x in range(width) for y in range(height)])

您提供信息的方式将创建25个子列表,每个25个元素,而该函数需要625个元素,没有任何子列表。