Python文本有阿尔法通道背景

时间:2014-05-27 10:27:52

标签: python png python-imaging-library alpha pillow

我正在使用Python 2.7.3和PIL / Pillow,并希望在保存为png的alpha_channel背景上创建文本(具有不透明度)。这是我的代码,它不完全正确,我希望:

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

以下代码是我正在寻找的,但背景完全透明/ 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

结果: enter image description here

1 个答案:

答案 0 :(得分:4)

问题是wm与文本颜色相同,因此如果您将文字绘制到文本上,您将无法看到任何内容。将wm的颜色更改为透明,就像我在下面所做的那样(并在初始化宽度,高度和不透明度后删除逗号):

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)