首页 > 解决方案 > 使用 Python37 运行时使用 Cloud Functions 生成缩略图

问题描述

我有一个由 Firebase 存储触发的 Google Cloud 功能,我想生成缩略图。

虽然 Node.js 文档有一个使用 ImageMagick 的示例,但 python 运行时没有这样的等价物。

牢记性能的可接受方法是什么?Pillow-SIMD会在云功能中工作吗?

或者我应该去 App Engine 生成缩略图并使用图像服务

标签: python-3.xfirebasegoogle-cloud-platformgoogle-cloud-functionsfirebase-storage

解决方案


您可以使用wandImageMagick 的绑定,以及google-cloud-storage在图像上传到存储桶后自动调整图像大小。

requirements.txt

google-cloud-storage
wand

main.py

from wand.image import Image
from google.cloud import storage

client = storage.Client()

PREFIX = "thumbnail"


def make_thumbnail(data, context):
    # Don't generate a thumbnail for a thumbnail
    if data['name'].startswith(PREFIX):
        return

    # Get the bucket which the image has been uploaded to
    bucket = client.get_bucket(data['bucket'])

    # Download the image and resize it
    thumbnail = Image(blob=bucket.get_blob(data['name']).download_as_string())
    thumbnail.resize(100, 100)

    # Upload the thumbnail with the filename prefix
    thumbnail_blob = bucket.blob(f"{PREFIX}-{data['name']}")
    thumbnail_blob.upload_from_string(thumbnail.make_blob())

然后您可以使用该gcloud工具进行部署:

$ gcloud beta functions deploy make_thumbnail \
    --runtime python37 \
    --trigger-bucket gs://[your-bucket-name].appspot.com

推荐阅读