gpt4 book ai didi

python - 如何使用 PIL 在半透明背景上创建重叠的半透明形状

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:08 27 4
gpt4 key购买 nike

我正在尝试创建在透明背景上绘制半透明形状的图像。由于某种原因,形状没有保持透明,而是完全覆盖了它们下面的形状。我的代码:

from PIL import Image, ImageDraw
img = Image.new("RGBA", (256, 256), (255,0,0,127))
drawing = ImageDraw.Draw(img, "RGBA")
drawing.ellipse((127-79, 127 - 63, 127 + 47, 127 + 63), fill=(0, 255, 0, 63), outline=(0, 255, 0, 255))
drawing.ellipse((127-47, 127 - 63, 127 + 79, 127 + 63), fill=(0, 0, 255, 63), outline=(0, 0, 255, 255))
img.save("foo.png", "png")

我希望结果看起来像(除了背景不透明):
expected
但它看起来像:
actual

当我尝试使用 img.save("foo.gif", "gif") 将其保存为 GIF 时,结果更糟。圆圈是实心的,轮廓和填充之间没有区别。

最佳答案

正如我在评论中提到的,ImageDraw.Draw 不进行混合——绘制的内容会替换之前存在的像素。要获得您想要的效果,需要分两步进行绘制。必须首先在空白透明背景上绘制椭圆,然后必须是alpha-composited。使用当前图像 (bg_img) 以保持透明度。

在下面的代码中,这已在可重用函数中实现:

from PIL import Image, ImageDraw


def draw_transp_ellipse(img, xy, **kwargs):
""" Draws an ellipse inside the given bounding box onto given image.
Supports transparent colors
"""
transp = Image.new('RGBA', img.size, (0,0,0,0)) # Temp drawing image.
draw = ImageDraw.Draw(transp, "RGBA")
draw.ellipse(xy, **kwargs)
# Alpha composite two images together and replace first with result.
img.paste(Image.alpha_composite(img, transp))


bg_img = Image.new("RGBA", (256, 256), (255, 0, 0, 127)) # Semitransparent background.

draw_transp_ellipse(bg_img, (127-79, 127-63, 127+47, 127+63),
fill=(0, 255, 0, 63), outline=(0, 255, 0, 255))
draw_transp_ellipse(bg_img, (127-47, 127-63, 127+79, 127+63),
fill=(0, 0, 255, 63), outline=(0, 0, 255, 255))

bg_img.save("foo.png")

这是它创建的图像,在我的图像文件编辑器应用程序中查看,该应用程序使用棋盘格图案呈现图像的半透明部分。如您所见,不透明的轮廓是唯一不透明的部分。

screenshot of image in image editor

关于python - 如何使用 PIL 在半透明背景上创建重叠的半透明形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54424056/

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