我需要以编程方式在纯色上创建一个文本蒙版,文本是透明的。
例如。
这可以使用 Imagemagick 或 Python 成像库来完成吗?
这与我想要的相反,因此透明背景上的纯文本。
convert -size 720x405 xc:transparent -fill pink -gravity center -pointsize 150 -font font.ttf -draw "text 0,0 CUT" output.png
如果可能的话,我更喜欢使用 PIL/Pillow。
更新:
这是我目前所拥有的......
font = ImageFont.truetype('font.ttf', 200, encoding='unic')
bg = Image.new('RGBA', (720, 404), '#0099ff')
mask = Image.new('1', (720, 404))
draw = ImageDraw.Draw(mask)
draw.text((0, 0), '#HELLO', font=font, fill='#ffffff')
bg.paste('#00000000', (0, 0), text)
bg.save('text.png', 'PNG')
但是,这会引发错误:
ValueError: unknown color specifier: '#00000000'
如果我设置为有效颜色,它会按预期工作,所以我知道我已经接近了,只是无法引用透明度。
更新:
最后我只是创建了另一个空白图像并使用它而不是定义颜色。所以:
trans = Image.new('RGBA', (720, 404))
bg.paste(trans, (0, 0), mask)