Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

python - How to draw text with image in background?

I want to make something like this python. Example Image

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 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()

Which, using the following BACKGROUND_IMAGE:

background image

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

result image produced

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

magnified section of resulting image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...