label_printer/gen_image.py

71 lines
2 KiB
Python

# SPDX-License-Identifier: GPL-3.0-or-later
from PIL import Image, ImageDraw, ImageFont
from colorama import Fore, Style
from config import *
from fonts import fonts
#font = "resources/ComicMono.ttf"
def gen_image(height, lines, font):
text_widths = []
for text in lines:
pil_font = ImageFont.truetype(font["path"], size=text["size"])
text["string"] = text["string"].replace("\r\n", "\n")
sub_lines = text["string"].split('\n')
text_widths.append(max([pil_font.getbbox(sub_line)[2] for sub_line in sub_lines]))
text_max_start = max([pil_font.getbbox(sub_line)[0] for sub_line in sub_lines])
# 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
if (text_max_start != 0):
print(Fore.YELLOW + "Warning, found situation where left corner of bbox of text != 0,", "text1_box:", text1, "text2_box", text2)
# the 1 here assures we don't get a 0 width image
text_widths.append(1)
width = max(text_widths)
# '1' is 1 bit bitdepth
img = Image.new('1', (width, height), color=1)
draw = ImageDraw.Draw(img)
for line in lines:
pil_font = ImageFont.truetype(font["path"], size=line["size"])
draw.text((0, line["pos"]), line["string"], font=pil_font, stroke_width = font["stroke_width_bold"] if line["bold"] else font["stroke_width"], stroke_fill="black")
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
Text1 = {
"string": "Hello world",
"size": 30,
"pos": 10,
"bold": False,
}
Text2 = {
"string": "Hello worhfeiheifhefld\nafefe",
"size": 20,
"pos": 40,
"bold": False,
}
Text3 = {
"string": "Hello worhfeiheifhefld\nafefe",
"size": 20,
"pos": 80,
"bold": False,
}
#gen_image(200, [Text1, Text2, Text3], fonts()["CYBER"])[2].save("aaa.png")