Last active
August 29, 2015 14:04
-
-
Save wiredfool/9aede43e76f0c13c1e2e to your computer and use it in GitHub Desktop.
Font opacity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.