Currently trying to have the same font for an image with PIL but with different sizes.
Tried to have two different font instances but it didn't work. How can I do that?
If you're using ImageFont.truetype()
, you'll need multiple instances for multiple sizes.
You could neatly wrap this using functools.lru_cache()
so a single font/size gets loaded only once during your app:
from functools import lru_cache
get_font = lru_cache()(ImageFont.truetype)
draw.text((10, 10), "hello", font=get_font("Arial.ttf", 10))
draw.text((10, 50), "world", font=get_font("Arial.ttf", 50))
I think you mean this:
#!/usr/bin/env python3
from PIL import Image, ImageFont, ImageDraw
# Create a black canvas
canvas = Image.new('RGB', (400,200))
# Get a drawing context
draw = ImageDraw.Draw(canvas)
monospace20 = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",20)
monospace50 = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",50)
draw.text((10, 10), "Hello 20", font=monospace20, fill=(255,255,255))
draw.text((10, 90), "Hello 50", font=monospace50, fill=(255,255,255))
canvas.save('result.png')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.