PIL:渐变文字

最近在工作中,需要使用python的PIL库来做一些图片处理,碰到一个需求是要在背景图片上生成带有渐变效果的文字,这里讲代码分析给大家,给大家提供一个参考。

需求图:

代码:

from PIL import ImageFont, ImageDraw, Image

if __name__ == "__main__":
    # 图片上的文字
    word = "Hello World"
    # 图片上文字的坐标
    word_position = (60, 430)
    # 文字字体和字号
    font = ImageFont.truetype("font/PingFang.ttc", 160)
    # 文字区域的box坐标
    word_box = font.getbbox(word)
    # 渐变颜色效果图片
    font_gradient_file_path = "template/font_gradient_1.jpg"
    
    # 生成文字区域的alpha图片
    font_gradient_im = Image.open(font_gradient_file_path)
    font_gradient_im = font_gradient_im.resize((word_box[2]-word_box[0], word_box[3]-word_box[1]))
    font_alpha = Image.new('L', font_gradient_im.size)
    font_alpha_d = ImageDraw.Draw(font_alpha)
    font_alpha_d.text((0,0), word , fill='White', anchor="lt", font=font)
    font_gradient_im.putalpha(font_alpha)
    
    # 将带有渐变效果的文字图片覆盖到背景图片上
    background_file_path = "template/background_template.png"
    im = Image.open(background_file_path)
    im.paste(font_gradient_im, word_position, font_gradient_im)
    
    # 保存图片
    im.save("result.png")

重点说明: word_box = font.getbbox(word)在设置了文字的字体和字号后,可以通过这个方法得到具体文字区域的大小。

有了文字区域的大小后,我们就可以通过font_gradient_im = font_gradient_im.resize((word_box[2]-word_box[0], word_box[3]-word_box[1]))动态的修改渐变颜色效果图片,以适配不同文字。

font_gradient_im.putalpha(font_alpha)通过在渐变颜色效果图片上增加一个文字的alpha通道,来实现文字的渐变。

im.paste(font_gradient_im, word_position, font_gradient_im)将渐变效果的文字覆盖到背景图片上,生成我们想要的图片。

需要以上代码的同学,可以在这里找到:

https://gitee.com/x_5/pil_example_gradient_fontopen in new window

代码中还另外提供了一种文字渐变效果,原理都是相通的,大家可以根据需要自行设计渐变的颜色效果图。

Last Updated:
Contributors: 小5