Skip to content

Instantly share code, notes, and snippets.

@hotohoto
Created June 19, 2024 07:44
Show Gist options
  • Save hotohoto/5d863e561c0ff99d23aa7d2aefc5b503 to your computer and use it in GitHub Desktop.
Save hotohoto/5d863e561c0ff99d23aa7d2aefc5b503 to your computer and use it in GitHub Desktop.
Draw text on an image using PIllow (auto font download)
from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
from urllib.request import urlopen
def check_and_get_font_path(font_name="roboto_regular") -> Path:
if font_name == "roboto_regular":
path = Path("font/Roboto-Regular.ttf")
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
url = "https://github.com/googlefonts/roboto/raw/main/src/hinted/Roboto-Regular.ttf"
with urlopen(url) as response, open(path, "wb") as out_file:
data = response.read()
out_file.write(data)
return path
else:
raise ValueError(f"Unknown font: {font_name}")
font = ImageFont.truetype(check_and_get_font_path(), 20)
...
draw = ImageDraw.Draw(image)
text_box = draw.textbbox((0, 0), label_text, font=font)
draw.rectangle(text_box, fill=(0, 0, 0, 255))
draw.text((0, 0), label_text, font=font, fill=(255, 255, 255, 255))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment