import base64
import zstd
from fastapi import FastAPI, File, UploadFile, Request, HTTPException, Response
from fastapi.responses import PlainTextResponse
app = FastAPI()
def get_media_type_from_bytes(data: bytes) -> str:
if data.startswith(b'\x89PNG\r\n\x1a\n'): return 'image/png'
if data.startswith(b'\xff\xd8'): return 'image/jpeg'
if data.startswith(b'GIF87a') or data.startswith(b'GIF89a'): return 'image/gif'
if data.startswith(b'RIFF') and data[8:12] == b'WEBP': return 'image/webp'
return 'application/octet-stream'
@app.post("/upload",
summary="이미지를 압축 후 URL-Safe Base64로 인코딩",
response_class=PlainTextResponse)
async def upload_safe_image(request: Request, file: UploadFile = File(...)):
image_bytes = await file.read()
compressed_bytes = zstd.compress(image_bytes, 22)
safe_b64_bytes = base64.urlsafe_b64encode(compressed_bytes)
safe_string = safe_b64_bytes.decode("utf-8")
image_url = request.url_for('get_safe_image', safe_string=safe_string)
return PlainTextResponse(content=str(image_url))
@app.get("/i/{safe_string}",
summary="URL-Safe Base64 문자열을 디코딩/압축 해제하여 이미지 제공")
async def get_safe_image(safe_string: str):
try:
b64_bytes = safe_string.encode("utf-8")
compressed_bytes = base64.urlsafe_b64decode(b64_bytes)
decoded_image_bytes = zstd.decompress(compressed_bytes)
except (ValueError, TypeError, zstd.ZstdError) as e:
raise HTTPException(status_code=400, detail=f"잘못된 데이터 형식입니다: {e}")
media_type = get_media_type_from_bytes(decoded_image_bytes)
return Response(content=decoded_image_bytes, media_type=media_type)단점
