使用PIL在Python中给图像添加透明圆形

4
我是一名有用的助手,可以为您进行文本翻译。
我有一个使用Python编写的程序,创建了一个带圆形的PNG文件。现在我想让这个圆形呈半透明状态,并给定一个alpha值。
以下是我的步骤:
img_map = Image.new(some arguments here)
tile = Image.open('tile.png')
img_map.paste(tile, (x,y))
canvas = ImageDraw.Draw(img_map)

# Now I draw the circle:
canvas.ellipse((p_x - 5, p_y - 5, p_x + 5, p_y + 5), fill=(255, 128, 10))

# now save and close
del canvas
img_map.save(path_out + file_name, 'PNG')

我该如何使椭圆形半透明?

谢谢。

2个回答

3

不要传递一个3元组RGB值,(255, 128, 10),而是传递一个4元组RGBA值:

canvas.ellipse((p_x - 5, p_y - 5, p_x + 5, p_y + 5), 
               fill=(255, 128, 10, 50))

例如,
import Image
import ImageDraw

img = Image.new('RGBA', size = (100, 100), color = (128, 128, 128, 255))
canvas = ImageDraw.Draw(img)

# Now I draw the circle:
p_x, p_y = 50, 50
canvas.ellipse((p_x - 5, p_y - 5, p_x + 5, p_y + 5), fill=(255, 128, 10, 50))

# now save and close
del canvas
img.save('/tmp/test.png', 'PNG')

enter image description here


嗨,我尝试过这个方法(在img的创建中使用了RGBA和4个项目),结果并不是很好。圆形的颜色不再完全鲜艳,但它不会与下面的地图混合......请看这里:http://i.imgur.com/d2b92Kv.png - otmezger
你可能想尝试Kris Kowal的解决方案在这里,或者也许是alpha合成函数(来自我在同一页上的帖子)。 - unutbu

0

我使用了Image.composite(background, foreground, mask)来在前景上遮罩一个半透明的圆形。

我按照这里的说明进行操作: PIL中将背景与透明图像合并

感谢@gareth-res


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接