gpt4 book ai didi

python - 如何在 python 中使用 wand 创建图像

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:43 25 4
gpt4 key购买 nike

我正在尝试创建一个 4 像素的图像:

1 个红色像素,1 个蓝色像素,1 个绿色像素,1 个白色像素

代码:

import wand.image

red = wand.image.Color('rgb(255,0,0)')
green = wand.image.Color('rgb(0,255,0)')
blue = wand.image.Color('rgb(0,0,255)')
white = wand.image.Color('rgb(255,255,255)')

myImage = wand.image.Image(width=2,height=2)

with wand.image.Image (myImage) as img:
img[0][0] = red
img[0][1] = blue
img[1][0] = green
img[1][1] = white
img.save(filename='out.png')

但它只创建一个透明的png。我究竟做错了什么?

最佳答案

Wand 的像素迭代器缺乏将颜色数据“同步”回 ImageMagick 的“真实”像素数据流的能力。

您可以实现导入像素数据流,like this question (类似的问题被问了很多)。

或者使用wand.drawing.Drawing API。

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color


with Drawing() as ctx:
colors = ["RED", "GREEN", "BLUE", "WHITE"]
for index, color_name in enumerate(colors):
ctx.push() # Grow context stack
ctx.fill_color = Color(color_name) # Allocated color
ctx.point(index % 2, index / 2) # Draw pixel
ctx.pop() # Reduce context stack
with Image(width=2, height=2, background=Color("NONE")) as img:
ctx.draw(img)
img.sample(100,100)
img.save(filename="output.png")

output.png

关于python - 如何在 python 中使用 wand 创建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46965943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com