具有 Alpha channel 背景的 Python 文本

标签 python python-imaging-library png alpha

我正在使用 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

最佳答案

问题是 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)

关于具有 Alpha channel 背景的 Python 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23887045/

相关文章:

python - 动态地从 PIL 提供图像

python - 使用 Anaconda 安装 Python 环境

python - Snow Leopard、Homebrew python 2.7、virtualenv、libjpeg 和 PIL = 导入错误

python - 在另一个函数 python 中使用一个函数的列表

python-3.x - 出现错误 "Could not import PIL.Image. The use of ` array_to_img` 需要 PIL。”

python:将base64编码的png图像转换为jpg

html - 将 png 与 css 堆叠在具有透明度的 div 中

image - WiX位图是否可以使用.png图像

python - 如何在类初始化期间添加在字符串中编码的动态方法?

python - 使用 TensorFlow 对图像进行自定义上采样