Saturday, June 3, 2023

Drawing with all the fonts available in Colab

import os
import unicodedata

from PIL import Image, ImageDraw, ImageFont

def get_fonts(default_size=20):
  fonts = []
  for root, dirs, files in os.walk('/usr/share/fonts/truetype/'):
    for file in files:
      if file.endswith('.ttf'):
        fonts.append(ImageFont.truetype(os.path.join(root, file), default_size))
  return fonts

TARGET_ALPHABET = [c for c in map(chr, range(128))
  if not unicodedata.category(c).startswith('C')]
FONTS = get_fonts()
WIDTH = 500

out = Image.new("RGB", (WIDTH, 2000), (255, 255, 255))

d = ImageDraw.Draw(out)

x = 0
y = 0
for c in TARGET_ALPHABET:
  for font in FONTS:
    d.text((x, y), c, font=font, fill=(0, 0, 0))
    left, top, right, bottom = d.textbbox((x, y), c, font=font)
    if right < WIDTH - 20:
      x = right + 5
    else:
      x = 0
      y = bottom + 5
out.show()
UNICODE CHARACTER DATABASE: General_Category Values ImageDraw.textbbox

No comments: