import uuid import io from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import FileResponse from pathlib import Path from PIL import Image import filetype app = FastAPI() STORAGE_DIR = Path("images") STORAGE_DIR.mkdir(exist_ok=True) @app.post("/") async def upload_image(file: UploadFile = File(...)): body = await file.read() kind = filetype.guess(body) if not kind or not kind.mime.startswith("image/"): raise HTTPException(status_code=400, detail="Chỉ chấp nhận file ảnh.") try: img = Image.open(io.BytesIO(body)) random_filename = f"{uuid.uuid4()}.webp" file_path = STORAGE_DIR / random_filename img.save(file_path, format="WEBP", quality=80) return { "filename": random_filename, } except Exception as e: raise HTTPException(status_code=500, detail=f"Lỗi xử lý ảnh: {str(e)}") @app.get("/{name}") async def get_image(name: str): file_path = STORAGE_DIR / name if not file_path.exists(): raise HTTPException(status_code=404, detail="NotFoundImage") return FileResponse(file_path, media_type="image/webp")