Reputation: 2702
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?
Upvotes: 0
Views: 2892
Reputation: 41
Here is how I upload the PIL Image file directly to Firebase storage bucket. I used BytesIO object image_stream to hold the image data in memory instead of saving it to a temporary file and then uploading this stream directly to Firebase Storage using blob.upload_from_file. Finally, I closed the BytesIO object to free up memory.
from firebase_admin import credentials, storage
from PIL import Image
from io import BytesIO
cred = credentials.Certificate("path_to_your_service_account_key.json")
firebase_admin.initialize_app(cred, {'storageBucket': 'your_storage_bucket_name.appspot.com'})
def upload_file_to_firebase(file, filename):
bucket = storage.bucket()
firebase_storage_path = f"images/{filename}"
image = Image.fromarray(file.astype('uint8'))
image_stream = BytesIO()
image.save(image_stream, format='JPEG')
image_stream.seek(0)
blob = bucket.blob(firebase_storage_path)
blob.upload_from_file(image_stream, content_type='image/jpg')
blob.make_public()
file_url = blob.public_url
# print("File uploaded to Firebase Storage and URL:", file_url)
image_stream.close()
return file_url
for idx, image in enumerate(imgs):
filename = f"{idx}.jpg"
upload_file_to_firebase(image, filename)
Upvotes: 0
Reputation: 35
This is how to directly upload the pillow image to firebase storage
from PIL import Image
from firebase_admin import credentials, initialize_app, storage
# Init firebase with your credentials
cred = credentials.Certificate("YOUR DOWNLOADED CREDENTIALS FILE (JSON)")
initialize_app(cred, {'storageBucket': 'YOUR FIREBASE STORAGE PATH (without gs://)'})
bucket = storage.bucket()
blob = bucket.blob('image.jpg')
bs = io.BytesIO()
im = Image.open("test_image.jpg")
im.save(bs, "jpeg")
blob.upload_from_string(bs.getvalue(), content_type="image/jpeg")
Upvotes: 1
Reputation: 15963
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)
Upvotes: 1