Using Python's Pillow Library: How To Draw Text Without Creating Draw Object Of An Image
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) ) dr
Solution 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/python3from PIL import Image, ImageFont, ImageDraw, ImageColor
defGenerateText(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:
Post a Comment for "Using Python's Pillow Library: How To Draw Text Without Creating Draw Object Of An Image"