61 lines
1.4 KiB
Python
61 lines
1.4 KiB
Python
import re
|
|
from io import BytesIO
|
|
from typing import Iterator
|
|
|
|
from fastapi import APIRouter, Depends
|
|
from fastapi.responses import StreamingResponse
|
|
from PIL import Image
|
|
|
|
from ..dav_file import DavFile
|
|
from ._common import FileNameLister, FilePrefixFinder, FilePrefixLoader
|
|
|
|
router = APIRouter(prefix="/image", tags=["image"])
|
|
|
|
_lister = FileNameLister(
|
|
remote_path="img",
|
|
re=re.compile(
|
|
r"\.(gif|jpe?g|tiff?|png|bmp)$",
|
|
flags=re.IGNORECASE,
|
|
),
|
|
)
|
|
|
|
_finder = FilePrefixFinder(_lister)
|
|
_loader = FilePrefixLoader(_finder)
|
|
|
|
|
|
@router.get("/list", response_model=list[str])
|
|
async def list_images(
|
|
image_file_names: Iterator[str] = Depends(_lister),
|
|
) -> list[str]:
|
|
return list(image_file_names)
|
|
|
|
|
|
@router.get("/find/{prefix}", response_model=list[str])
|
|
async def find_images(
|
|
file_names: Iterator[str] = Depends(_finder),
|
|
) -> list[str]:
|
|
return list(file_names)
|
|
|
|
|
|
@router.get(
|
|
"/get/{prefix}",
|
|
response_class=StreamingResponse,
|
|
responses=_loader.responses,
|
|
)
|
|
async def get_image(
|
|
prefix: str,
|
|
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)
|
|
img_buffer.seek(0)
|
|
|
|
return StreamingResponse(
|
|
content=img_buffer,
|
|
media_type="image/jpeg",
|
|
headers={
|
|
"Content-Disposition": f"filename={prefix}.jpg"
|
|
},
|
|
)
|