Created
November 19, 2021 22:10
-
-
Save nelsondev19/35910eff9c09ca015cfb4748be345133 to your computer and use it in GitHub Desktop.
Optimization of images with FastAPI (Python)
This file contains 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
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 DEVICES | |
def 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.thumbnail(size_defined) | |
image.save(PATH_FILES + str(size['height']) + "_" + filename) | |
print("success") | |
@app.post("/upload/file") | |
async def upload_file(background_tasks: BackgroundTasks, file: UploadFile = File(...)): | |
# SAVE FILE ORIGINAL | |
with open(PATH_FILES + file.filename, "wb") as myfile: | |
content = await file.read() | |
myfile.write(content) | |
myfile.close() | |
# RESIZE IMAGES | |
background_tasks.add_task(resize_image, filename=file.filename) | |
return JSONResponse(content={"message": "success"}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment