PIL:在图像顶部绘制透明文本
PIL: draw transparent text on top of an image
在我的一个项目中,我试图在一些文本上创建轮廓。总体思路是从原来的白色文本中偏移一个稍微透明的黑色文本。
由于某些原因,我得到的是黑色文本,但下面是透明的。这是 MCVE:
image = Image.open("spongebob.gif").convert("RGBA")
draw = ImageDraw.Draw(image, "RGBA")
font = ImageFont.truetype("impact.ttf", 25)
draw.text((0, 0), "This text should be 5% alpha", fill=(0, 0, 0, 15), font=font)
image.save("foo.gif")
结果:
我错过了什么?
这应该适合您。
from PIL import Image, ImageDraw, ImageFont
image = Image.open("spongebob.gif").convert("RGBA")
txt = Image.new('RGBA', image.size, (255,255,255,0))
font = ImageFont.truetype("impact.ttf", 25)
d = ImageDraw.Draw(txt)
d.text((0, 0), "This text should be 5% alpha", fill=(0, 0, 0, 15), font=font)
combined = Image.alpha_composite(image, txt)
combined.save("foo.gif")
编辑:Pillow 文档中的参考示例 http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text
在我的一个项目中,我试图在一些文本上创建轮廓。总体思路是从原来的白色文本中偏移一个稍微透明的黑色文本。
由于某些原因,我得到的是黑色文本,但下面是透明的。这是 MCVE:
image = Image.open("spongebob.gif").convert("RGBA")
draw = ImageDraw.Draw(image, "RGBA")
font = ImageFont.truetype("impact.ttf", 25)
draw.text((0, 0), "This text should be 5% alpha", fill=(0, 0, 0, 15), font=font)
image.save("foo.gif")
结果:
我错过了什么?
这应该适合您。
from PIL import Image, ImageDraw, ImageFont
image = Image.open("spongebob.gif").convert("RGBA")
txt = Image.new('RGBA', image.size, (255,255,255,0))
font = ImageFont.truetype("impact.ttf", 25)
d = ImageDraw.Draw(txt)
d.text((0, 0), "This text should be 5% alpha", fill=(0, 0, 0, 15), font=font)
combined = Image.alpha_composite(image, txt)
combined.save("foo.gif")
编辑:Pillow 文档中的参考示例 http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text