Optimization of images with FastAPI

Optimization of Images with FastAPI (Python)


pip3 install FastAPI uvicorn Pillow

Background Tasks

You can define background tasks to be run after returning a response.

from fastapi import FastAPI, UploadFile, File, BackgroundTasks
from fastapi.responses import JSONResponse
from os import getcwd
from PIL import Image
app = FastAPI()PATH_FILES = getcwd() + "/"# RESIZE IMAGES FOR DIFFERENT DEVICESdef resize_image(filename: str):
sizes = [{
"width": 1280,
"height": 720
}, {
"width": 640,
"height": 480
for size in sizes:
size_defined = size['width'], size['height']
image = Image.open(PATH_FILES + filename, mode="r")
image.save(PATH_FILES + str(size['height']) + "_" + filename)
async def upload_file(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
# SAVE FILE ORIGINALwith open(PATH_FILES + file.filename, "wb") as myfile:
content = await file.read()
# RESIZE IMAGESbackground_tasks.add_task(resize_image, filename=file.filename)
return JSONResponse(content={"message": "success"})


dogs.jpg # Original Image720_dogs.jpg # Resolution 1280 x 720480_dogs.jpg # Resolution 640 x 480



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store