Search code examples
pythonfontspathpython-imaging-librarygoogle-cloud-storage

How to load fonts from GCS


I want to load "fonts" from Google Storage, I've try two ways, but none of them work. Any pointers? Appreciated for any advices provided.

First:

I follow the instruction load_font_from_gcs(uri)given in the answer here, but I received an NameError: name 'load_font_from_gcs' is not defined message. I installed google storage dependency and execute from google.cloud import storage

.

Second:

I try to execute the following code (reference #1) , and running into an blob has no attribute open() error, just the same answer I get it here, but as the reference in this link, it give a positive answer. enter image description here

reference #1

bucket = storage_client.bucket({bucket_name})
blob = bucket.get_blob({blob_name) 
with blob.open("r") as img:
  imgblob = Image.open(img)
  draw = ImageDraw.Draw(imgblob)

Solution

  • According to the provided links, your code must use BytesIO in order to work with the font file loaded from GCS.
    The load_font_from_gcs is a custom function, written by the author of that question you referencing.
    And it is not represented in the google-cloud-storage package.

    Next, according to the official Google Cloud Storage documentation here:
    Files from storage can be accessed this way (this example loads the font file into the PIL.ImageFont.truetype):

    # Import PIL
    from PIL import Image, ImageFont, ImageDraw
    
    # Import the Google Cloud client library
    from google.cloud import storage
    
    # Import BytesIO module
    from io import BytesIO
    
    # Instantiate a client
    storage_client = storage.Client()
    
    # The name of the bucket
    bucket_name = "my-new-bucket"
    
    # Required blob
    blob_name = "somefont.otf"
    
    # Creates the bucket & blob instance
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    
    # Download the given blob
    blob_content = blob.download_as_string()
    
    # Make ImageFont out of it (or whatever you want)
    font = ImageFont.truetype(BytesIO(font_file), 18)
    

    So, your reference code can be changed respectively:

    bucket = storage_client.bucket({bucket_name})
    blob = bucket.get_blob({blob_name).download_as_string()
    bytes = BytesIO(blob)
    imgblob = Image.open(bytes)
    draw = ImageDraw.Draw(imgblob)
    

    You can read more about PIL here.
    Also, don't forget to check the official Google Cloud Storage documentation.
    (There are plenty of examples using Python code.)