更新时间:2023-09-20 18:59:52
您可以创建一个函数来创建一块空画布并在其中绘制文本并将其作为 PIL Image
返回,如下所示:
You can make a function that creates a piece of empty canvas and draws text in and returns it as a PIL Image
like this:
#!/usr/local/bin/python3
from PIL import Image, ImageFont, ImageDraw, ImageColor
def GenerateText(size, fontname, fontsize, bg, fg, text, position):
"""Generate a piece of canvas and draw text on it"""
canvas = Image.new('RGBA', size, bg)
# Get a drawing context
draw = ImageDraw.Draw(canvas)
font = ImageFont.truetype(fontname, fontsize)
draw.text(position, text, fg, font=font)
return canvas
# Create empty yellow image
im = Image.new('RGB',(400,100),'yellow')
# Generate two text overlays - a transparent one and a blue background one
w, h = 200, 100
transparent = (0,0,0,0)
textoverlay1 = GenerateText((w,h), 'Arial', 16, transparent, 'magenta', "Magenta/transparent", (20,20))
textoverlay2 = GenerateText((w,h), 'Apple Chancery', 20, 'blue', 'black', "Black/blue", (20,20))
# Paste overlay with transparent background on left, and blue one on right
im.paste(textoverlay1, mask=textoverlay1)
im.paste(textoverlay2, (200,0), mask=textoverlay2)
# Save result
im.save('result.png')
这是粘贴前的初始黄色图像:
Here's the initial yellow image before pasting:
这是粘贴两个叠加层后的结果:
And here's the result after pasting the two overlays: