使用python的pillow库:如何在不创建图像的绘制对象的情况下绘制文本

2023-11-30

下面的代码展示了如何通过创建绘图对象在图像上写入文本

from PIL import Image, ImageFont, ImageDraw

image =  Image.new(mode = "RGBA" , size= (500, 508) )

draw = ImageDraw.Draw(image)

font = ImageFont.load("arial.pil")

draw.text((10, 10), "hello", font=font)

我要求的是如何将文本作为枕头对象返回,这样我就可以将其粘贴到另一个图像上,而不必创建图像对象并绘制对象,然后在其上写入文本,我只想将原始文本作为枕头对象稍后在 .paste() 函数中使用它。 类似的东西(代码不存在,但这是我可以想象的):

from PIL import Image, ImageFont, ImageDraw

image =  Image.new(mode = "RGBA" , size= (500, 508) )

font = ImageFont.load("arial.pil")

text = font.loadtext("hello") #imaginary part (a pillow object)

image.paste(text, (10,10))

您可以创建一个函数来创建一块空画布并绘制文本并将其作为PIL Image像这样:

#!/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')

这是粘贴前的初始黄色图像:

enter image description here

这是粘贴两个叠加层后的结果:

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用python的pillow库:如何在不创建图像的绘制对象的情况下绘制文本 的相关文章

随机推荐