Search code examples
pythonpython-imaging-librarypngalpha

Python text with alpha channel background


I'm working with Python 2.7.3 and PIL/Pillow and want to create text (with opacity) on an alpha_channel background saved as png. Here is my code which doesn't do exactly, what I was hoping:

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageEnhance

width=854
height=480
opacity=0.8
text='copyright'
filename = 'result.png'
black = (0,0,0)
white = (255,255,255)

font = ImageFont.truetype('verdana.ttf',15)
wm = Image.new('RGBA',(width,height),white)
im = Image.new('L',(width,height),0)

draw = ImageDraw.Draw(wm)
w,h = draw.textsize(text, font)
draw.text(((width-w)/2,(height-h)/2),text,white,font)

en = ImageEnhance.Brightness(wm)
#en.putalpha(mask)
mask = en.enhance(1-opacity)
im.paste(wm,(25,25),mask)

im.save(filename)

Result: result

The following code is what I'm looking for, but the background fully transparent/alpha_channel:

import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

width = 854
height = 480
black = (0,0,0)
text = "copyright"
white = (255,255,255)
font = ImageFont.truetype("Arial.ttf",40)
img = Image.new("RGBA", (width,height),white)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(text, font)
draw.text(((width-w)/2,(height-h)/2),text,black,font=font)
draw = ImageDraw.Draw(img)
#img.putalpha
img.save("result.png")
#img.show

Result: enter image description here


Solution

  • The problem is that wm has the same color as the text, so you won't see anything if you draw the text onto it. Change the color of wm to transparent, like I did below (and remove the commas after initializing of width, height and opacity):

    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont
    from PIL import ImageEnhance
    
    width=854
    height=480
    opacity=0.8
    text='copyright'
    filename = 'result.png'
    black = (0,0,0)
    white = (255,255,255)
    transparent = (0,0,0,0)
    
    font = ImageFont.truetype('verdana.ttf',15)
    wm = Image.new('RGBA',(width,height),transparent)
    im = Image.new('RGBA',(width,height),transparent) # Change this line too.
    
    draw = ImageDraw.Draw(wm)
    w,h = draw.textsize(text, font)
    draw.text(((width-w)/2,(height-h)/2),text,white,font)
    
    en = ImageEnhance.Brightness(wm)
    #en.putalpha(mask)
    mask = en.enhance(1-opacity)
    im.paste(wm,(25,25),mask)
    
    im.save(filename)