96 lines
3.0 KiB
Python
96 lines
3.0 KiB
Python
import sys
|
|
import os
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
import tempfile
|
|
|
|
class Label():
|
|
pixels_x = 155
|
|
pixels_y = 106
|
|
bg_color = (255, 255, 255)
|
|
|
|
def __init__(self, skip_create = False):
|
|
me_path = os.path.dirname(__file__)
|
|
self.bold_font_fname = os.path.join(me_path, 'OpenSans-Bold.ttf')
|
|
self.regular_font_fname = os.path.join(me_path, 'OpenSans-Regular.ttf')
|
|
|
|
if not skip_create:
|
|
self.create()
|
|
|
|
def create(self):
|
|
self.img = Image.new('RGB', (self.pixels_x, self.pixels_y), color=self.bg_color)
|
|
|
|
def draw_text(self, text : str, pos_x, pos_y, color=(0,0,0), size=10, font_file=None, centered_x=False, centered_y=False, scale_to_fit=False):
|
|
d = ImageDraw.Draw(self.img)
|
|
if font_file is None or font_file == 'regular':
|
|
font_file = self.regular_font_fname
|
|
elif font_file == 'bold':
|
|
font_file = self.bold_font_fname
|
|
|
|
font_fits = False
|
|
orig_size = size
|
|
orig_pos_x = pos_x
|
|
orig_pos_y = pos_y
|
|
while not font_fits:
|
|
fnt = ImageFont.truetype(font_file, size)
|
|
w, h = d.textsize(text, font=fnt)
|
|
|
|
if centered_x:
|
|
pos_x = orig_pos_x - w / 2
|
|
else:
|
|
pos_x = orig_pos_x
|
|
|
|
if centered_y:
|
|
pos_y = orig_pos_y - h / 2
|
|
else:
|
|
pos_y = orig_pos_y
|
|
|
|
if not scale_to_fit:
|
|
font_fits = True
|
|
break
|
|
|
|
if pos_x >= 0 and pos_x + w <= self.pixels_x:
|
|
font_fits = True
|
|
else:
|
|
size = size - 1
|
|
if size != orig_size:
|
|
print('Rescaled font to size:', size)
|
|
|
|
d.text((pos_x, pos_y), text, font=fnt, fill=color)
|
|
|
|
def save(self, fname = None):
|
|
"""
|
|
Save Label to file. If no fname is supplied, a tempfile is created and its filename is returend
|
|
"""
|
|
if self.img is None:
|
|
raise Exception('Must create image first')
|
|
|
|
if fname is None or fname == '':
|
|
fobj = tempfile.mkstemp(suffix='.png', prefix='label_', text=False)
|
|
with os.fdopen(fobj[0], mode="w+b") as file:
|
|
self.img.save(file, format='PNG')
|
|
fname = fobj[1]
|
|
else:
|
|
self.img.save(fname)
|
|
|
|
return fname
|
|
|
|
def get_pillow_image(self):
|
|
return self.img
|
|
|
|
|
|
class MiceToiletLabel(Label):
|
|
|
|
pixels_x = 155
|
|
pixels_y = 106
|
|
|
|
def __init__(self):
|
|
super().__init__(skip_create=True)
|
|
self.create()
|
|
|
|
def put_text(self, heading, line1=None, line2=None):
|
|
self.draw_text(heading, self.pixels_x/2, 20, size=25, font_file='bold', centered_x=True, centered_y=True, scale_to_fit=True)
|
|
if line1:
|
|
self.draw_text(line1, self.pixels_x/2, 55, size=20, centered_x=True, centered_y=True, scale_to_fit=True)
|
|
if line2:
|
|
self.draw_text(line2, self.pixels_x/2, 85, size=20, centered_x=True, centered_y=True, scale_to_fit=True)
|