如何在背景中绘制带有图像的文本?

How to draw text with image in background?

我想做这样的东西python。

我在背景中有图像,并用透明填充书写文本,以便显示图像。

这是我发现的一种使用 Image.composite() 函数的方法,该函数记录在 here and here.

@Mark Ransom 在 answer to the question
Is it possible to mask an image in Python Imaging Library (PIL)? 中(非常)简洁地描述了使用的方法……以下只是应用它来完成您想要做的事情的示例。

from PIL import Image, ImageDraw, ImageFont

BACKGROUND_IMAGE_FILENAME = 'cookie_cutter_background_cropped.png'
RESULT_IMAGE_FILENAME = 'cookie_cutter_text_result.png'
THE_TEXT = 'LOADED'
FONT_NAME = 'arialbd.ttf'  # Arial Bold

# Read the background image and convert to an RGB image with Alpha.
with open(BACKGROUND_IMAGE_FILENAME, 'rb') as file:
    bgr_img = Image.open(file)
    bgr_img = bgr_img.convert('RGBA')  # Give iamge an alpha channel.
    bgr_img_width, bgr_img_height = bgr_img.size
    cx, cy = bgr_img_width//2, bgr_img_height//2  # Center of image.

# Create a transparent foreground to be result of non-text areas.
fgr_img = Image.new('RGBA', bgr_img.size, color=(0, 0, 0, 0))

font_size = bgr_img_width//len(THE_TEXT)
font = ImageFont.truetype(FONT_NAME, font_size)

txt_width, txt_height = font.getsize(THE_TEXT)  # Size of text w/font if rendered.
tx, ty = cx - txt_width//2, cy - txt_height//2  # Center of text.

mask_img = Image.new('L', bgr_img.size, color=255)
mask_img_draw = ImageDraw.Draw(mask_img)
mask_img_draw.text((tx, ty), THE_TEXT, fill=0, font=font, align='center')

res_img = Image.composite(fgr_img, bgr_img, mask_img)
res_img.save(RESULT_IMAGE_FILENAME)
res_img.show()

其中,使用以下BACKGROUND_IMAGE

生成了如下所示的图像,它是在 Photoshop 中查看的,因此可以辨认出它的透明背景(不按比例):

这是一张放大图,显示了平滑渲染的字符边缘: