Heroo
Heroo

Reputation: 122

Is possible to link an online font file to PIL ImageFont.truetype()?

Instead of downloading the font locally and link it to ImageFont.truetyp() to be like this:

from pillow import ImageFont
font = ImageFont.truetype('Roboto-Regular.ttf', size=10)

Can I do something like this:

from pillow import ImageFont
font = ImageFont.truetype('https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf', size=10)

Upvotes: 0

Views: 2168

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

ImageFont.true_type takes a file-like object.

Python's standard library, urllib.request.urlopen returns a file-like object.

The following should work:

from pillow import ImageFont
from urllib.request import urlopen

truetype_url = 'https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true'
font = ImageFont.truetype(urlopen(truetype_url), size=10)

edit: As @flyer2403 answered, to make that particular url work you need to add ?raw=true to the end.

Upvotes: 8

flyer2403
flyer2403

Reputation: 1299

Just needed to make a slight change to @PeterWood's answer to make this work on google colab:

truetype_url = 'https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true'

I needed to add ?raw=true to the end of the truetype_url

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207465

You should be able to download the contents of the font with requests and then make a file-like object out of them with BytesIO to pass to ImageFont.truetype() in place of the filename:

#!/usr/bin/env python3

from PIL import Image, ImageFont, ImageDraw
import requests
import io

# Load font from URI
r = requests.get('https://github.com/ProgrammingFonts/ProgrammingFonts/raw/master/Droid-Sans-Mono/droid-sans-mono-1.00/Droid%20Sans%20Mono.ttf', allow_redirects=True)
font = ImageFont.truetype(io.BytesIO(r.content), size=24)

# Create a black canvas and get drawing context
canvas = Image.new('RGB', (400,200))
draw = ImageDraw.Draw(canvas)

# Write in our font
draw.text((10, 10), "Hello, nice to meet you.", font=font, fill=(255,255,255))

canvas.save('result.png')

enter image description here

I can't work out the correct URL for your font, so I used a random, different one.

Upvotes: 1

Related Questions