label_printer/gen_image.py

102 lines
3.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"
# TODO: this really needs a more descriptive name
def gen_image(label_width, lines, font, landscape: bool, spacing=0):
text_widths = []
# the 1 here assures we don't get a 0 height image
lowest_pixels = []
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])
y_cursor = text["pos"]
for sub_line in sub_lines:
y_cursor += pil_font.getbbox(sub_line)[3] + spacing
y_cursor -= spacing
lowest_pixels.append(y_cursor)
# 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)
max_width = max(text_widths)
if landscape:
# the 1 here assures we don't get a 0 width image
text_widths.append(1)
width = max_width
height = label_width
else:
# the 1 here assures we don't get a 0 height image
lowest_pixels.append(1)
height = max(lowest_pixels)
width = label_width
# '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", spacing=spacing)
message = None
status = None
if not landscape and max_width > label_width:
message = f"WARNING: Your text is too long to fit on a landscape mode label, and will therefore be cut off.\nEither change the orientation of the label to landscape, change the font size, or break up the text into multiple lines"
status = "Info"
if (width > max_label_length):
message = f"Label too long, max allowed length = {max_label_length}, yours = {width}."
status = "Error"
elif (height > max_label_length):
message = f"Label too long, max allowed length = {max_label_length}, yours = {height}."
status = "Error"
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"], True)[2].save("aaa.png")
# gen_image(200, [Text1, Text2, Text3], fonts()["CYBER"], False, 4)[2].save("bbb.png")