Using python's pillow library: how to draw text without creating draw object of an image

社会主义新天地 提交于 2020-07-07 07:31:10

问题


the code bellow shows how to write text on image with creating a draw object

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)

what i'm asking for is how to return the text as a pillow object so i can just paste it on another images without having to create image object and draw object then writing text on them, i just want the raw text as a pillow object to use it later in .paste() function. something like (code doesn't exist but it's what i can imagine):

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

回答1:


You can make a function that creates a piece of empty canvas and draws text in and returns it as a PIL Image like this:

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

Here's the initial yellow image before pasting:

And here's the result after pasting the two overlays:



来源:https://stackoverflow.com/questions/61742298/using-pythons-pillow-library-how-to-draw-text-without-creating-draw-object-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!