63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
import uuid
|
|
from io import BytesIO
|
|
|
|
from PIL import Image
|
|
from fastapi import FastAPI, UploadFile
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
|
|
def generate_uuid_from_file(file_content):
|
|
namespace_oid = uuid.UUID("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
|
|
return uuid.uuid5(namespace_oid, str(file_content))
|
|
|
|
|
|
app = FastAPI(
|
|
prefix="/api",
|
|
tags=["Сервак для загрузки"],
|
|
)
|
|
|
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
|
|
|
|
@app.post("/upload_avatar", response_model=dict[str, str])
|
|
async def upload_avatar(file: UploadFile):
|
|
content = await file.read()
|
|
name = generate_uuid_from_file(content)
|
|
image = Image.open(BytesIO(content))
|
|
|
|
new_size = (512, 512)
|
|
image_url = f"static/images/avatars/{name}_avatar.{image.format.lower()}"
|
|
if image.format.lower() == "gif":
|
|
frames = []
|
|
try:
|
|
while True:
|
|
frames.append(image.copy())
|
|
image.seek(image.tell() + 1)
|
|
except EOFError:
|
|
pass
|
|
resized_frames = [frame.resize(new_size) for frame in frames]
|
|
resized_gif = resized_frames[0]
|
|
resized_gif.save(
|
|
image_url,
|
|
save_all=True,
|
|
append_images=resized_frames[1:],
|
|
optimize=True,
|
|
duration=image.info["duration"],
|
|
loop=image.info["loop"]
|
|
)
|
|
else:
|
|
resized_image = image.resize(new_size)
|
|
|
|
resized_image.save(image_url)
|
|
return {"image_url": image_url}
|
|
|
|
|
|
@app.post("/upload_image", response_model=dict[str, str])
|
|
async def upload_image(file: UploadFile):
|
|
content = await file.read()
|
|
name = generate_uuid_from_file(content)
|
|
image = Image.open(BytesIO(content))
|
|
|
|
image_url = f"static/images/images/{name}_image.{image.format.lower()}"
|
|
image.save(image_url, save_all=True) if image.format.lower() in {"gif"} else image.save(image_url)
|
|
return {"image_url": image_url}
|