Last active
May 25, 2025 05:06
-
-
Save Burekasim/8f98e5882554a9d3bca5976ef7a3a359 to your computer and use it in GitHub Desktop.
Python script to resize images via Cloud Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functions_framework | |
from flask import Request, Response | |
from google.cloud import storage | |
from PIL import Image | |
import io | |
import mimetypes | |
# Set your bucket name here | |
BUCKET_NAME = 'my-resize-bucket-poc' | |
@functions_framework.http | |
def resize_image(request: Request) -> Response: | |
# Parse query parameters | |
image_path = request.args.get('image') | |
size_str = request.args.get('size') | |
if not image_path or not size_str: | |
return Response("Missing 'image' or 'size' query parameter", status=400) | |
# Parse size | |
try: | |
width, height = map(int, size_str.lower().split('x')) | |
except ValueError: | |
return Response("Invalid size format. Use WIDTHxHEIGHT, e.g., 300x200", status=400) | |
# Download image from GCS | |
client = storage.Client() | |
bucket = client.bucket(BUCKET_NAME) | |
blob = bucket.blob(image_path) | |
if not blob.exists(): | |
return Response(f"Image not found: {image_path}", status=404) | |
image_data = blob.download_as_bytes() | |
# Resize image using Pillow | |
try: | |
with Image.open(io.BytesIO(image_data)) as img: | |
img = img.convert("RGBA") if img.mode in ("P", "LA") else img | |
resized_img = img.resize((width, height), Image.Resampling.LANCZOS) | |
buffer = io.BytesIO() | |
mime_type, _ = mimetypes.guess_type(image_path) | |
image_format = mime_type.split("/")[-1].upper() if mime_type else "PNG" | |
resized_img.save(buffer, format=image_format) | |
buffer.seek(0) | |
return Response( | |
response=buffer.read(), | |
status=200, | |
content_type=mime_type or "image/png", | |
headers={"Cache-Control": "public, max-age=3600"} | |
) | |
except Exception as e: | |
return Response(f"Error processing image: {e}", status=500) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment