label_printer/flask/gen_image.py

43 lines
1.3 KiB
Python
Raw Normal View History

2024-09-14 13:29:58 +00:00
from PIL import Image, ImageDraw, ImageFont
from colorama import Fore, Style
from printer_info import *
2024-09-14 18:49:57 +00:00
def gen_image(height, text1, text2):
font1 = ImageFont.truetype("ComicMono.ttf", size=text1["size"])
font2 = ImageFont.truetype("ComicMono.ttf", size=text2["size"])
2024-09-14 13:29:58 +00:00
2024-09-14 18:49:57 +00:00
text1_box = font1.getbbox(text1["string"])
text2_box = font2.getbbox(text2["string"])
2024-09-14 13:29:58 +00:00
text1_width = text1_box[2]
text2_width = text2_box[2]
# 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 (text1_box[0] != 0 or text2_box[0] != 0):
print(Fore.YELLOW + "Warning, found situation where left corner of bbox of text != 0,", "text1_box:", text1_box, "text2_box", text2_box)
2024-09-14 18:49:57 +00:00
# the 1 here assures we don't get a 0 width image
img = Image.new('1', (max(text1_width, text2_width, 1), height), color=1)
2024-09-14 13:29:58 +00:00
draw = ImageDraw.Draw(img)
2024-09-14 18:49:57 +00:00
draw.text((0, text1["pos"]), text1["string"], font=font1)
draw.text((0, text2["pos"]), text2["string"], font=font2)
2024-09-14 13:29:58 +00:00
return img
2024-09-14 18:49:57 +00:00
Text1 = {
"string": "Hello world",
"size": 30,
"pos": 10,
}
Text2 = {
"string": "Hello worhfeiheifhefld",
"size": 20,
"pos": 40,
}
gen_image(label_width, Text1, Text2).save('output.png')