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

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

本文介绍了如何在背景中绘制带有图像的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作像这样的python.

I want to make something like this python.

我将图片放在背景中,并用透明填充文字,以便显示图片.

I have the image in background and write text with transparent fill, so that image shows up.

推荐答案

这是我发现使用Image.composite()函数执行此操作的一种方法,该函数记录在此处此处.

Here's one way I found to do it using the Image.composite() function which is documented here and here.

此问题的答案(非常)简要描述了使用的方法. "https://stackoverflow.com/questions/28358379/is-it-possible-to-mask-an-image-in-python-imaging-library-pil>是否可以在Python Imaging Library中屏蔽图像( PIL)? @Mark Ransom撰写的……下面仅是应用它来完成您想要做的事的说明.

The approach used is described (very) tersely in this answer to the question
Is it possible to mask an image in Python Imaging Library (PIL)? by @Mark Ransom…the following is just an illustration of applying it to accomplish what you want do.

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 image with alpha.
with open(BACKGROUND_IMAGE_FILENAME, 'rb') as file:
    bgr_img = Image.open(file)
    bgr_img = bgr_img.convert('RGBA')  # Make sure it has alpha.
    bgr_img_width, bgr_img_height = bgr_img.size
    cx, cy = bgr_img.size[0] // 2, bgr_img.size[1] // 2 # Image center.

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

# Create a mask layer and render the text string onto it.
font_size = bgr_img_width // len(THE_TEXT)
font = ImageFont.truetype(FONT_NAME, font_size)

txt_width, txt_height = font.getsize(THE_TEXT)
tx, ty = cx - txt_width//2, cy - txt_height//2  # Center 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中查看的,因此可以辨认出它的透明背景(不按比例缩放):

produced the image shown below, which is it being viewed in Photoshop so the transparent background it has would be discernible (not to scale):

这里是放大图,显示了平滑绘制的字符边缘:

Here's an enlargement, showing the smoothly rendered edges of the characters:

这篇关于如何在背景中绘制带有图像的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:27