Search code examples
pythonfirebasepython-imaging-libraryfirebase-storage

Python: upload Pillow Image to Firebase storage bucket


I'm trying to figure out how to upload a Pillow Image instance to a Firebase storage bucket. Is this possible?

Here's some code:

from PIL import Image

image = Image.open(file)
# how to upload to a firebase storage bucket?

I know there's a gcloud-python library but does this support Image instances? Is converting the image to a string my only option?


Solution

  • The gcloud-python library is the correct library to use. It supports uploads from Strings, file pointers, and local files on the file system (see the docs).

    from PIL import Image
    from google.cloud import storage
    
    client = storage.Client()
    bucket = client.get_bucket('bucket-id-here')
    blob = bucket.blob('image.png')
    # use pillow to open and transform the file
    image = Image.open(file)
    # perform transforms
    image.save(outfile)
    of = open(outfile, 'rb')
    blob.upload_from_file(of)
    # or... (no need to use pillow if you're not transforming)
    blob.upload_from_filename(filename=outfile)