Skip to main content (Source)

import logging
import os
from io import BytesIO
from pathlib import PurePath
import azure.functions as func
from azure.identity import DefaultAzureCredential
from import BlobServiceClient, ContentSettings
from PIL import Image, UnidentifiedImageError
credential = DefaultAzureCredential()
THUMB_PREFIX = "thumb_"
def get_crop(size):
    Get the crop coordinates given the source image sizes
        size (tuple)  - the (width, height) of the image
    shortest_edge = min(size)
    centers = (size[0] // 2, size[1] // 2)
    return (
        centers[0] - shortest_edge // 2,
        centers[1] - shortest_edge // 2,
        centers[0] + shortest_edge // 2,
        centers[1] + shortest_edge // 2,
def main(myblob: func.InputStream):
    Generate thumbnails from incoming blob if it's an image and
    upload the thumbnail blob to the same location but with a
    file name prefix.
    source_path = PurePath(
    source_name =
    container_name =[0]
    source_path = source_path.relative_to(container_name)
    if container_name != CONTAINER_NAME:
        # Strange, we're suppose to only react to events in the data container
    if source_name.startswith(THUMB_PREFIX):
        # This is already a thumbnail so we can just leave it
        # Attempt to open the file as an image. If it's not, too bad so sad.
        source_image =
    except UnidentifiedImageError:
        f"Resizing image blob: \n" f"Name: {}\n" f"URI: {myblob.uri}\n"
    # Crop a square in the center and resize to thumbnail size
    thumb_image = source_image.crop(get_crop(source_image.size))
    thumb_image = thumb_image.resize((THUMB_SIZE, THUMB_SIZE))
    thumb_path = source_path.parent / (THUMB_PREFIX +
    thumb_stream = BytesIO(), format=source_image.format)
    with BlobServiceClient(
        account_url=ACCOUNT_URL, credential=credential
    ) as storage, storage.get_container_client(CONTAINER_NAME) as data_container:
            "Uploading image %s to %s. %s bytes",
        # Rewind to the start of the stream after .save wrote to it.
        with data_container.upload_blob(
        ) as out_blob:
  "Created image thumbnail: %s", out_blob.url)