forked from ping/newsrack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_utils.py
More file actions
89 lines (77 loc) · 2.69 KB
/
_utils.py
File metadata and controls
89 lines (77 loc) · 2.69 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Copyright (c) 2022 https://github.com/ping/
#
# This software is released under the GNU General Public License v3.0
# https://opensource.org/licenses/GPL-3.0
import textwrap
from PIL import Image, ImageDraw, ImageFont # type: ignore
from _recipe_utils import CoverOptions
def generate_cover(
file_name: str,
title_text: str,
cover_options: CoverOptions,
):
"""
Generate a plain image cover file
:param file_name: Filename to be saved as
:param title_text: Cover text
:param cover_options: Cover options
:return:
"""
font_title = ImageFont.truetype(
cover_options.title_font_path, cover_options.title_font_size
)
font_date = ImageFont.truetype(
cover_options.datestamp_font_path, cover_options.datestamp_font_size
)
rectangle_offset = 25
title_texts = [t.strip() for t in title_text.split(":")]
img = Image.new(
"RGB",
(cover_options.cover_width, cover_options.cover_height),
color=cover_options.background_colour,
)
img_draw = ImageDraw.Draw(img)
# rectangle outline
img_draw.rectangle(
(
rectangle_offset,
rectangle_offset,
cover_options.cover_width - rectangle_offset,
cover_options.cover_height - rectangle_offset,
),
width=2,
outline=cover_options.text_colour,
)
total_height = 0
line_gap = 25
text_w_h = []
for i, text in enumerate(title_texts):
if i == 0:
wrapper = textwrap.TextWrapper(width=15)
word_list = wrapper.wrap(text=text)
for ii in word_list[:-1]:
_, __, text_w, text_h = img_draw.textbbox((0, 0), ii, font=font_title)
text_w_h.append([ii, text_w, text_h, text_h, font_title])
total_height += text_h + line_gap
_, __, text_w, text_h = img_draw.textbbox(
(0, 0), word_list[-1], font=font_title
)
text_w_h.append([word_list[-1], text_w, text_h, text_h, font_title])
total_height += text_h + line_gap
else:
_, __, text_w, text_h = img_draw.textbbox((0, 0), text, font=font_title)
text_w_h.append([text, text_w, text_h, text_h, font_date])
total_height += text_h + line_gap
cumu_offset = 0
for text, text_w, text_h, h_offset, font in text_w_h:
img_draw.text(
(
int((cover_options.cover_width - text_w) / 2),
int((cover_options.cover_height - total_height) / 2) + cumu_offset,
),
text,
font=font,
fill=cover_options.text_colour,
)
cumu_offset += h_offset
img.save(file_name)