AdventImage.hide_text

This commit is contained in:
Jörn-Michael Miehe 2022-10-14 23:35:17 +00:00
parent b93f95020d
commit 12c46acf69
2 changed files with 49 additions and 31 deletions

View file

@ -1,3 +1,4 @@
import colorsys
from dataclasses import dataclass
import numpy as np
@ -81,3 +82,49 @@ class AdventImage:
mean_color: np.ndarray = np.mean(pixel_data, axis=0)
return tuple(mean_color.astype(int).tolist())
async def hide_text(
self,
xy: tuple[float, float],
text: str | bytes,
font: "ImageFont._Font",
anchor: str | None = "mm",
**text_kwargs,
) -> None:
# betroffenen Bildbereich bestimmen
text_box = await self.get_text_box(
xy=xy,
text=text,
font=font,
anchor=anchor,
**text_kwargs
)
if text_box is not None:
# Durchschnittsfarbe bestimmen
text_color = await self.get_average_color(
box=text_box,
)
# etwas heller/dunkler machen
tc_h, tc_s, tc_v = colorsys.rgb_to_hsv(*text_color)
tc_v = int((tc_v - 127) * 0.97) + 127
if tc_v < 127:
tc_v += 3
else:
tc_v -= 3
text_color = colorsys.hsv_to_rgb(tc_h, tc_s, tc_v)
text_color = tuple(int(val) for val in text_color)
# Buchstaben verstecken
ImageDraw.Draw(self.img).text(
xy=xy,
text=text,
font=font,
fill=text_color,
anchor=anchor,
**text_kwargs
)

View file

@ -1,11 +1,10 @@
import colorsys
import re
# from datetime import date
from io import BytesIO
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from PIL import ImageDraw, ImageFont
from PIL import ImageFont
from ..dav_common import dav_get_file, dav_list_files
from ._image import AdventImage
@ -102,40 +101,12 @@ async def get_picture_for_day(
xy = tuple(rnd.choices(range(30, 470), k=2))
# betroffenen Bildbereich bestimmen
text_box = await adv_img.get_text_box(
await adv_img.hide_text(
xy=xy,
text=letter,
font=font,
)
if text_box is not None:
# Durchschnittsfarbe bestimmen
text_color = await adv_img.get_average_color(
box=text_box,
)
# etwas heller/dunkler machen
tc_h, tc_s, tc_v = colorsys.rgb_to_hsv(*text_color)
tc_v = int((tc_v - 127) * 0.97) + 127
if tc_v < 127:
tc_v += 3
else:
tc_v -= 3
text_color = colorsys.hsv_to_rgb(tc_h, tc_s, tc_v)
text_color = tuple(int(val) for val in text_color)
# Buchstaben verstecken
ImageDraw.Draw(adv_img.img).text(
xy=xy,
text=letter,
font=font,
anchor="mm",
fill=text_color,
)
# Bilddaten in Puffer laden
img_buffer = BytesIO()
adv_img.img.save(img_buffer, format="JPEG", quality=85)