Skip to content

Instantly share code, notes, and snippets.

@wiredfool
Last active August 29, 2015 14:04
Show Gist options
  • Save wiredfool/9aede43e76f0c13c1e2e to your computer and use it in GitHub Desktop.
Save wiredfool/9aede43e76f0c13c1e2e to your computer and use it in GitHub Desktop.
Font opacity
from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('Pillow/Tests/images/lena.png').convert('RGBA')
# make a blank image for the text
txt = Image.new('RGBA', base.size)
# get a font
fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
d = ImageDraw.Draw(txt) # drawing context
# draw text, half opacity
d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))
# draw text, full opacity
d.text((10,60), "World", font=fnt, fill=(255,255,255,255))
out = Image.alpha_composite(base, txt)
out.show()
@wiredfool
Copy link
Author

In this version, the fill parameter is a 4-tuple, of (R,G,B,A). The txt image is now an RGBA so there's a place for the alpha parameter to land.

So, we're actually drawing the text with the alpha that we want to use when compositing it in. ImageDraw.text doesn't do alpha composite, it only blats in the bits, so we have to do that step ourselves.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment