Skip to content

Commit

Permalink
add Google Cloud Function for converting HEIC to JPEG
Browse files Browse the repository at this point in the history
  • Loading branch information
ElinaZoldnere committed Jul 4, 2024
1 parent b4c7a6c commit 0c4d818
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
41 changes: 41 additions & 0 deletions cloud-function/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import functions_framework
import pyheif
from PIL import Image
import io
from flask import send_file, request, abort

import os
SECRET_TOKEN = os.getenv('SECRET_TOKEN')

@functions_framework.http
def convert_heic_to_jpg(request):
if request.headers.get('Authorization') != f"Bearer {SECRET_TOKEN}":
abort(403)

if 'file' not in request.files:
return 'No file part', 400

file = request.files['file']

if file.filename == '':
return 'No selected file', 400

try:
heif_file = pyheif.read_heif(io.BytesIO(file.read()))
image = Image.frombytes(
heif_file.mode,
heif_file.size,
heif_file.data,
"raw",
heif_file.mode,
heif_file.stride,
)

output = io.BytesIO()
image.save(output, format="JPEG") # Use 'JPEG' instead of 'JPG'
output.seek(0)

return send_file(output, mimetype='image/jpeg', as_attachment=True, download_name='converted.jpg')

except Exception as e:
return str(e), 500
5 changes: 5 additions & 0 deletions cloud-function/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Flask==2.0.2
functions-framework==3.0.0
pyheif==0.6.1
Pillow==8.4.0
Werkzeug==2.0.2

0 comments on commit 0c4d818

Please sign in to comment.