ovdashboard/api/ovdashboard_api/routers/image.py

62 lines
1.4 KiB
Python
Raw Normal View History

2022-08-31 10:21:24 +00:00
import re
from io import BytesIO
from typing import Iterator
2022-08-31 10:21:24 +00:00
2022-09-02 14:51:11 +00:00
from fastapi import APIRouter, Depends
2022-08-31 10:21:24 +00:00
from fastapi.responses import StreamingResponse
from PIL import Image
from ..dav_file import DavFile
from ._common import FileNameLister, FilePrefixLoader, PrefixFinder
2022-08-31 10:21:24 +00:00
router = APIRouter(prefix="/image", tags=["image"])
2022-09-02 13:22:35 +00:00
_lister = FileNameLister(
remote_path="img",
re=re.compile(
r"\.(gif|jpe?g|tiff?|png|bmp)$",
flags=re.IGNORECASE,
),
2022-08-31 10:21:24 +00:00
)
_finder = PrefixFinder(_lister)
2022-09-02 14:51:11 +00:00
_loader = FilePrefixLoader(_finder)
2022-08-31 10:21:24 +00:00
@router.get("/list", response_model=list[str])
async def list_images(
2022-09-02 13:22:35 +00:00
image_file_names: Iterator[str] = Depends(_lister),
2022-08-31 10:21:24 +00:00
) -> list[str]:
return list(image_file_names)
@router.get("/find/{prefix}", response_model=list[str])
async def find_images(
2022-09-02 13:22:35 +00:00
file_names: Iterator[str] = Depends(_finder),
2022-08-31 10:21:24 +00:00
) -> list[str]:
return list(file_names)
@router.get(
"/get/{prefix}",
2022-08-31 14:03:29 +00:00
response_class=StreamingResponse,
2022-09-02 14:51:11 +00:00
responses=_loader.responses,
2022-08-31 10:21:24 +00:00
)
async def get_image(
prefix: str,
2022-09-02 14:51:11 +00:00
dav_file: DavFile = Depends(_loader),
) -> str:
img = Image.open(BytesIO(await dav_file.bytes)).convert("RGB")
img_buffer = BytesIO()
img.save(img_buffer, format='JPEG', quality=85)
2022-08-31 10:21:24 +00:00
img_buffer.seek(0)
return StreamingResponse(
2022-08-31 10:41:36 +00:00
content=img_buffer,
2022-08-31 10:21:24 +00:00
media_type="image/jpeg",
headers={
"Content-Disposition": f"filename={prefix}.jpg"
},
)