label_printer/gen_image.py

61 lines
1.9 KiB
Python
Raw Normal View History

2024-09-25 19:48:36 +00:00
# SPDX-License-Identifier: GPL-3.0-or-later
2024-09-14 13:29:58 +00:00
from PIL import Image, ImageDraw, ImageFont
from colorama import Fore, Style
from config import *
2024-09-14 13:29:58 +00:00
2024-11-27 23:59:36 +00:00
#font = "resources/ComicMono.ttf"
2024-11-27 23:59:36 +00:00
def gen_image(height, text1, text2, font):
font1 = ImageFont.truetype(font["path"], size=text1["size"])
font2 = ImageFont.truetype(font["path"], size=text2["size"])
2024-09-14 13:29:58 +00:00
2024-09-15 10:24:26 +00:00
text1["string"] = text1["string"].replace("\r\n", "\n")
text2["string"] = text2["string"].replace("\r\n", "\n")
2024-09-14 13:29:58 +00:00
2024-09-15 10:24:26 +00:00
lines1 = text1["string"].split('\n')
lines2 = text2["string"].split('\n')
text1_width = max([font1.getbbox(line)[2] for line in lines1])
text2_width = max([font2.getbbox(line)[2] for line in lines2])
text1_max_start = max([font1.getbbox(line)[0] for line in lines1])
text2_max_start = max([font2.getbbox(line)[0] for line in lines2])
2024-09-14 13:29:58 +00:00
# I am assuming the left corner of the bbox to always be 0, I have yet to
# encounter a situation when this isn't the case
2024-09-15 10:24:26 +00:00
if (text1_max_start != 0 or text2_max_start != 0):
print(Fore.YELLOW + "Warning, found situation where left corner of bbox of text != 0,", "text1_box:", text1, "text2_box", text2)
2024-09-14 13:29:58 +00:00
2024-09-14 18:49:57 +00:00
# the 1 here assures we don't get a 0 width image
width = max(text1_width, text2_width, 1)
img = Image.new('1', (width, height), color=1)
2024-09-14 13:29:58 +00:00
draw = ImageDraw.Draw(img)
2024-11-27 23:59:36 +00:00
draw.text((0, text1["pos"]), text1["string"], font=font1, stroke_width=font["stroke_width"], stroke_fill="black")
2024-09-14 18:49:57 +00:00
draw.text((0, text2["pos"]), text2["string"], font=font2)
2024-09-14 13:29:58 +00:00
if (width > max_label_length):
message = f"Label too long, max allowed length = {max_label_length}, yours = {width}."
status = "Error"
else:
message = None
status = None
return message, status, img
2024-09-14 13:29:58 +00:00
2024-09-14 18:49:57 +00:00
Text1 = {
"string": "Hello world",
"size": 30,
"pos": 10,
}
Text2 = {
2024-09-15 10:24:26 +00:00
"string": "Hello worhfeiheifhefld\nafefe",
2024-09-14 18:49:57 +00:00
"size": 20,
"pos": 40,
}