PIL: draw transparent text on top of an image
Question:
In a project I have, I am trying to create an outline over some text. The overall idea is to offset a black text slightly transparent from the original white text.
For some reasons, I get the black text but nether in transparent. Here is the 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")
The result:
What did I miss?
Answers:
This should work for you.
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")
edit: The reference example from the Pillow documentation
https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#example-draw-partial-opacity-text
In a project I have, I am trying to create an outline over some text. The overall idea is to offset a black text slightly transparent from the original white text.
For some reasons, I get the black text but nether in transparent. Here is the 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")
The result:
What did I miss?
This should work for you.
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")
edit: The reference example from the Pillow documentation
https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#example-draw-partial-opacity-text