Skip to content

Instantly share code, notes, and snippets.

@c2t-r
Last active December 2, 2023 09:17
Show Gist options
  • Save c2t-r/b4072ea77caa92f6e551a6cc4ea87e1e to your computer and use it in GitHub Desktop.
Save c2t-r/b4072ea77caa92f6e551a6cc4ea87e1e to your computer and use it in GitHub Desktop.
PIL draw with spacing and alpha
from PIL import Image, ImageDraw, ImageFont

def drawText(bg, text: str, spacing: int, font, origin, color):
    img_clear = Image.new("RGBA", bg.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(img_clear)
    origin_x, origin_y = origin

    pads = []
    for i in text:
        draw.text((origin_x + sum(pads), origin_y), i, font=font, fill=color)
        pads.extend([font.getbbox(i)[2], spacing])

    return Image.alpha_composite(bg, img_clear)

args

drawText(image, text, 0, font, (X, Y), (R, G, B))
arg value type
1 image PIL.Image
2 text str
3 character spacing int
4 font PIL.ImageFont
5 position int(tuple)
6 color int(tuple)

example

from PIL import Image, ImageDraw, ImageFont

def drawText(bg, text: str, spacing: int, font, origin, color):
    img_clear = Image.new("RGBA", bg.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(img_clear)
    origin_x, origin_y = origin

    pads = []
    for i in text:
        draw.text((origin_x + sum(pads), origin_y), i, font=font, fill=color)
        pads.extend([font.getbbox(i)[2], spacing])

    return Image.alpha_composite(bg, img_clear)
    
image = Image.new("RGBA", (1024, 512), (100, 200, 255))
for i in range(0, image.width, 100):
    image.paste((0, 0, 0), (i, 0, i+50, image.height))

font = ImageFont.truetype("font.ttf", size=45)
text_image = drawText(image, "Hello World", 30, font, (100, 200), (255, 255, 200))
text_image = drawText(text_image, "Good Morning", 10, font, (200, 400), (255, 100, 200, 150))
text_image = drawText(text_image, "Good Night", -60, font, (800, 100), (155, 100, 255, 40))
text_image.save("output.png")

output

normal draw

from PIL import Image, ImageDraw, ImageFont

image = Image.new("RGBA", (1024, 512), (100, 200, 255))
for i in range(0, image.width, 100):
    image.paste((0, 0, 0), (i, 0, i+50, image.height))

font = ImageFont.truetype("font.ttf", size=45)
draw = ImageDraw.Draw(image)
draw.text((100, 200), "Hello World", font=font, fill=(255, 255, 200))
draw.text((200, 400), "Good Morning", font=font, fill=(255, 100, 200, 150))
draw.text((800, 100), "Good Night", font=font, fill=(155, 100, 255, 40))
image.save("output_.png")

output_

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment