Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating thumbnails with Cloud Functions using the Python37 runtime

I have a Google Cloud Function triggered by Firebase Storage, and I want to generate thumbnails.

While the Node.js docs have an example that uses ImageMagick there is no such equivalent for the python runtime.

What would be an acceptable approach keeping performance in mind ? Would Pillow-SIMD work in a cloud function ?

Or should I go App Engine for thumbnail generation and use the Images service ?

like image 750
Florian d'Erfurth Avatar asked Oct 19 '25 05:10

Florian d'Erfurth


1 Answers

You can use wand, a binding to ImageMagick, along with google-cloud-storage to resize an image automatically once it's uploaded to a storage bucket.

In requirements.txt:

google-cloud-storage
wand

In 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())

Then you can deploy it with the gcloud tool:

$ gcloud beta functions deploy make_thumbnail \
    --runtime python37 \
    --trigger-bucket gs://[your-bucket-name].appspot.com
like image 166
Dustin Ingram Avatar answered Oct 20 '25 19:10

Dustin Ingram