简体   繁体   English

使用PIL在Python上的图像上添加透明圆圈

[英]Adding a transparent circle to an image on python with PIL

I have a python program that craetes a png file with a circle on it. 我有一个python程序,该程序可在png文件上放一个圆圈。 Now I want this circle to be semi transparent, given an alpha value. 现在,给定一个alpha值,我希望这个圆是半透明的。

Here is what I do: 这是我的工作:

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')

how can I make the ellipse semi transparent? 如何使椭圆半透明?

Thanks 谢谢

Instead of a 3-tuple RGB value, (255, 128, 10), pass a 4-tuple RGBA value: 传递3元组RGBA值,而不是3元组RGB值(255、128、10):

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

For example, 例如,

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')

在此处输入图片说明

I used Image.composite(background, foreground, mask) to mask a semi transparent circle on a foreground. 我使用Image.composite(background, foreground, mask)遮罩了前景上的半透明圆。

I followed the instructions from here: Merging background with transparent image in PIL 我按照这里的指示进行操作: 在PIL中将背景与透明图像合并

Thanks to @gareth-res 感谢@ gareth-res

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM