E-Paper-Calendar/Calendar/DesignEntity.py

62 lines
2 KiB
Python
Raw Normal View History

from PIL import Image, ImageOps, ImageDraw
2019-04-05 11:37:51 +02:00
from Assets import colors
2019-04-08 11:20:04 +02:00
masking_threshold = 200
2019-03-07 21:27:30 +01:00
2019-07-13 08:05:35 +02:00
class DesignEntity (object):
"""General entity that can be drawn on to a panel design or
other design entities."""
2019-07-13 08:05:35 +02:00
def __init__(self, size, mask=False, invert_mask=False, color_key=False):
self.size = size
2020-04-21 14:00:01 +02:00
# Are dimensions >= 0?
2020-04-28 13:30:29 +02:00
if self.size[0] < 0:
self.size = (0, self.size[1])
if self.size[1] < 0:
self.size = (self.size[0], 0)
2020-04-21 14:00:01 +02:00
self.pos = (0, 0)
2019-02-28 22:19:33 +01:00
self.mask = mask
self.invert_mask = invert_mask
self.__init_image__()
self.__finished_image__ = False
2019-03-07 21:27:30 +01:00
self.color_key = color_key
2019-07-13 08:05:35 +02:00
def __init_image__(self, color=colors["bg"]):
rounded_size = (int(self.size[0]), int(self.size[1]))
2019-07-12 13:46:50 +02:00
self.__image__ = Image.new('RGBA', rounded_size, color=color)
2019-07-13 08:05:35 +02:00
def get_image(self):
if self.__finished_image__ is False:
self.__finish_image__()
self.__finished_image__ = True
return self.__image__
2019-07-13 08:05:35 +02:00
def draw(self, subimage, pos, mask=False, invert_mask=False, color_key=False):
rounded_pos = (int(pos[0]), int(pos[1]))
2019-02-28 22:19:33 +01:00
img_mask = None
if mask:
2019-07-13 08:05:35 +02:00
img_mask = self.__get_mask__(
subimage, invert_mask=invert_mask, color_key=color_key)
self.__image__.paste(subimage, rounded_pos, mask=img_mask)
2019-07-13 08:05:35 +02:00
def draw_design(self, entity):
self.draw(entity.get_image(), entity.pos, entity.mask,
entity.invert_mask, entity.color_key)
2019-07-13 08:05:35 +02:00
def draw_image(self, path, pos):
self.draw(Image.open(path), pos)
2019-07-13 08:05:35 +02:00
def __finish_image__(self):
pass
2019-07-13 08:05:35 +02:00
def __get_mask__(self, image, invert_mask, color_key):
2019-03-07 21:27:30 +01:00
mask = image.convert('L')
if color_key:
2019-07-13 08:05:35 +02:00
mask = mask.point(lambda p: 0 if p <
masking_threshold else 255, '1').convert('L')
2019-03-07 21:27:30 +01:00
if invert_mask:
mask = ImageOps.invert(mask)
2019-07-13 08:05:35 +02:00
return ImageOps.invert(mask)