1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
# ========================================================================== #
# #
# KVMD - The main PiKVM daemon. #
# #
# Copyright (C) 2020 Maxim Devaev <[email protected]> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
# ========================================================================== #
import sys
import os
import io
import functools
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from ... import aiotools
# =====
async def make_text_jpeg(width: int, height: int, quality: int, text: str) -> bytes:
return (await aiotools.run_async(_inner_make_text_jpeg, width, height, quality, text))
@functools.lru_cache(maxsize=10)
def _inner_make_text_jpeg(width: int, height: int, quality: int, text: str) -> bytes:
image = Image.new("RGB", (width, height), color=(0, 0, 0))
draw = ImageDraw.Draw(image)
draw.multiline_text((20, 20), text, font=_get_font(), fill=(255, 255, 255))
with io.BytesIO() as bio:
image.save(bio, format="jpeg", quality=quality)
return bio.getvalue()
@functools.lru_cache()
def _get_font() -> ImageFont.FreeTypeFont:
module_path = sys.modules[__name__].__file__
assert module_path is not None
path = os.path.join(os.path.dirname(module_path), "fonts", "Azbuka04.ttf")
return ImageFont.truetype(path, size=20)
|