GRS
GRS

Reputation: 3084

Loading fonts into ImageFont from GCS

I am having problems loading fonts in memory, directly from GCS, without creating temporary files.

The goal is to load it into:

from PIL import Image, ImageFont, ImageDraw
BUCKET_NAME = 'bucket_name'
gs_path = 'path_in_bucket/object.otf'
font_file = load_font_from_gcs(gs_path)
font = ImageFont.truetype(font_file, 18)

I tried using the following 2 functions to download:

from google.cloud import storage

storage_client = storage.Client()

def load_font_from_gcs(gs_path):
    font_file = download_blob_as_string(gs_path)
    return font_file

def download_blob_as_string(source_blob_name, bucket_name=BUCKET_NAME):
    """Downloads a blob from the bucket as string."""

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    return blob.download_as_string()

However, I keep running into encoding/decoding errors or type errors e.g.

File "/anaconda3/envs/ml36/lib/python3.6/site-packages/PIL/ImageFont.py", line 161, in init font, size, index, encoding, layout_engine=layout_engine TypeError: argument 1 must be encoded string without null bytes, not bytes

Upvotes: 0

Views: 545

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207530

Wrapping it in a BytesIO works on my Mac:

from io import BytesIO
...
...
font_file = load_font_from_gcs(gs_path)
font = ImageFont.truetype(BytesIO(font_file), 18)

Upvotes: 1

Related Questions