label_image.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import sys
  2. import os
  3. from PIL import Image, ImageDraw, ImageFont
  4. import tempfile
  5. class Label():
  6. pixels_x = 155
  7. pixels_y = 106
  8. bg_color = (255, 255, 255)
  9. def __init__(self, skip_create = False):
  10. me_path = os.path.dirname(__file__)
  11. self.bold_font_fname = os.path.join(me_path, 'OpenSans-Bold.ttf')
  12. self.regular_font_fname = os.path.join(me_path, 'OpenSans-Regular.ttf')
  13. if not skip_create:
  14. self.create()
  15. def create(self):
  16. self.img = Image.new('RGB', (self.pixels_x, self.pixels_y), color=self.bg_color)
  17. def draw_text(self, text : str, pos_x, pos_y, color=(0,0,0), size=10, font_file=None, centered=False, scale_to_fit=False):
  18. d = ImageDraw.Draw(self.img)
  19. if font_file is None or font_file == 'regular':
  20. font_file = self.regular_font_fname
  21. elif font_file == 'bold':
  22. font_file = self.bold_font_fname
  23. font_fits = False
  24. orig_size = size
  25. orig_pos_x = pos_x
  26. orig_pos_y = pos_y
  27. while not font_fits:
  28. fnt = ImageFont.truetype(font_file, size)
  29. w, h = d.textsize(text, font=fnt)
  30. if centered:
  31. pos_x = orig_pos_x - w / 2
  32. pos_y = orig_pos_y - h / 2
  33. else:
  34. pos_x = orig_pos_x
  35. pos_y = orig_pos_y
  36. if not scale_to_fit:
  37. font_fits = True
  38. break
  39. if pos_x >= 0 and pos_x + w <= self.pixels_x:
  40. font_fits = True
  41. else:
  42. size = size - 1
  43. if size != orig_size:
  44. print('Rescaled font to size:', size)
  45. d.text((pos_x, pos_y), text, font=fnt, fill=color)
  46. def save(self, fname = None):
  47. """
  48. Save Label to file. If no fname is supplied, a tempfile is created and its filename is returend
  49. """
  50. if self.img is None:
  51. raise Exception('Must create image first')
  52. if fname is None or fname == '':
  53. fobj = tempfile.mkstemp(suffix='.png', prefix='label_', text=False)
  54. with os.fdopen(fobj[0], mode="w+b") as file:
  55. self.img.save(file, format='PNG')
  56. fname = fobj[1]
  57. else:
  58. self.img.save(fname)
  59. return fname
  60. class MiceToiletLabel(Label):
  61. pixels_x = 155
  62. pixels_y = 106
  63. def __init__(self):
  64. super().__init__(skip_create=True)
  65. self.create()
  66. def put_text(self, heading, line1=None, line2=None):
  67. self.draw_text(heading, self.pixels_x/2, 20, size=25, font_file='bold', centered=True, scale_to_fit=True)
  68. if line1:
  69. self.draw_text(line1, self.pixels_x/2, 55, size=20, centered=True, scale_to_fit=True)
  70. if line2:
  71. self.draw_text(line2, self.pixels_x/2, 85, size=20, centered=True, scale_to_fit=True)