Python:将Pillow Image上传到Firebase存储桶

wlwcrazw  于 2023-10-22  发布在  Python
关注(0)|答案(3)|浏览(157)

我正在尝试弄清楚如何将PillowImage示例上传到Firebase存储桶。这可能吗?
下面是一些代码:

from PIL import Image

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

我知道有一个gcloud-python库,但它支持Image示例吗?将图像转换为字符串是我唯一的选择吗?

qf9go6mv

qf9go6mv1#

gcloud-python库是要使用的正确库。它支持从文件系统上的字符串、文件指针和本地文件上传(参见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)
z4bn682m

z4bn682m2#

这是如何直接上传枕头图像到Firebase存储

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")
gopyfrb3

gopyfrb33#

下面是我如何将PIL映像文件直接上传到Firebase存储桶。我使用BytesIO对象image_stream将图像数据保存在内存中,而不是将其保存到临时文件中,然后使用blob.upload_from_file将此流直接上传到Firebase Storage。最后,我关闭了BytesIO对象以释放内存。

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)

相关问题