Python 3.x 使用python';s枕头库:如何在不创建图像绘制对象的情况下绘制文本

Python 3.x 使用python';s枕头库:如何在不创建图像绘制对象的情况下绘制文本,python-3.x,python-imaging-library,Python 3.x,Python Imaging Library,下面的代码演示了如何通过创建绘图对象在图像上写入文本 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) 我要问的是如何将文本作为枕头对

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

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()函数中使用它。 类似(代码不存在,但我能想象得到):


您可以创建一个函数,创建一块空画布,在其中绘制文本,并将其作为
PIL图像返回,如下所示:

#!/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')
以下是粘贴前的初始黄色图像:

下面是粘贴两个覆盖层后的结果:


我的回答解决了你的问题吗?如果是这样,请考虑接受它作为您的答案-点击空心蜱/支票旁边的选票计数。如果没有,请说出什么不起作用,以便我或其他人可以进一步帮助您。谢谢
#!/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')