split functions

This commit is contained in:
Jörn-Michael Miehe 2022-10-10 18:44:01 +00:00
parent b6e9ade1b2
commit 25019c8ccc

View file

@ -76,6 +76,38 @@ async def load_picture_standard() -> Image.Image:
return img.convert("RGB") return img.convert("RGB")
async def get_text_box(
img: Image.Image,
xy: tuple[float, float],
text: str | bytes,
font: "ImageFont._Font",
anchor: str | None = "mm",
**text_kwargs,
) -> tuple[int, int, int, int] | None:
mask = Image.new(mode="1", size=img.size, color=0)
ImageDraw.Draw(mask).text(
xy=xy,
text=text,
font=font,
anchor=anchor,
fill=1,
**text_kwargs,
)
return mask.getbbox()
async def get_average_color(
img: Image.Image,
box: tuple[int, int, int, int],
) -> tuple[int, int, int]:
pixel_data = img.crop(box).getdata()
mean_color: np.ndarray = np.mean(pixel_data, axis=0)
return tuple(mean_color.astype(int).tolist())
@router.get( @router.get(
"/picture/{index}", "/picture/{index}",
response_class=StreamingResponse, response_class=StreamingResponse,
@ -85,29 +117,28 @@ async def get_picture_for_day(
img: Image.Image = Depends(load_picture_standard), img: Image.Image = Depends(load_picture_standard),
) -> StreamingResponse: ) -> StreamingResponse:
font = ImageFont.truetype("Lena.ttf", 50) font = ImageFont.truetype("Lena.ttf", 50)
xy = (200, 150)
txt_layer = Image.new(mode="RGB", size=(400, 400), color=(0, 0, 0)) text_box = await get_text_box(
txt_color = (255, 255, 255) img=img,
xy=xy,
ImageDraw.Draw(txt_layer).text(
xy=(300, 300),
text=letter, text=letter,
font=font, font=font,
anchor="mm",
fill=txt_color,
) )
if (bbox := txt_layer.getbbox()) is not None: if text_box is not None:
mean = np.mean(img.crop(bbox).getdata(), axis=0) text_color = await get_average_color(
txt_color = tuple(int(val) for val in mean) img=img,
box=text_box,
)
ImageDraw.Draw(img).text( ImageDraw.Draw(img).text(
xy=(300, 300), xy=xy,
text=letter, text=letter,
font=font, font=font,
anchor="mm", anchor="mm",
fill=txt_color, fill=text_color,
) )
img_buffer = BytesIO() img_buffer = BytesIO()
img.save(img_buffer, format="PNG", quality=85) img.save(img_buffer, format="PNG", quality=85)