Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL: draw transparent text on top of an image

Tags:

python

pillow

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:

Sponge Bob not happy

What did I miss?

like image 282
FunkySayu Avatar asked Nov 05 '17 16:11

FunkySayu


People also ask

How do I Pil an image?

Image. open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).


1 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 http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text

like image 134
Alex Jadczak Avatar answered Sep 20 '22 15:09

Alex Jadczak