答案 0 :(得分:3)
我发现使用Image.composite()
函数执行此操作的方法有here和here。
@Mark Ransom在问题answer的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 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中被查看,因此它具有透明背景(不按比例):
这是一个放大图,显示了字符的平滑渲染边缘: