From c6a1f114ec6ab2da71a94cdf07a2416c226a914c Mon Sep 17 00:00:00 2001 From: CMDR furrycat Date: Wed, 10 Jan 2018 16:13:59 +0000 Subject: [PATCH] Use separate mask image if available. --- plugin/bling/bling.py | 41 +++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/plugin/bling/bling.py b/plugin/bling/bling.py index 37039d7..58ada2f 100644 --- a/plugin/bling/bling.py +++ b/plugin/bling/bling.py @@ -17,6 +17,7 @@ class Bling(object): self.path = os.path.dirname(__file__)[(len(os.getcwd()) + 1):] self.fgname = 'fg.png' self.bgname = 'bg.png' + self.maskname = 'mask.png' def valid_commands(self): return ['bling'] @@ -144,7 +145,7 @@ class Bling(object): await client.send_typing(message.channel) - data = self.create_avatar(parsed['url'], os.sep.join([self.path, profile, self.bgname]), os.sep.join([self.path, profile, self.fgname])) + data = self.create_avatar(parsed['url'], os.sep.join([self.path, profile, self.bgname]), os.sep.join([self.path, profile, self.fgname]), os.sep.join([self.path, profile, self.maskname])) if data is None: await cat.yelp(message.channel) return @@ -152,13 +153,25 @@ class Bling(object): text = ' '.join(parsed['mentions']) if parsed['mentions'] is not None else 'purr' await bot.say(message.channel, text, attachment = bot.parse_attachment(data, parsed['filename'] + '.png')) - def create_avatar(self, url, bgfile, fgfile): + def create_avatar(self, url, bgfile, fgfile, maskfile = None): # Get bling images. - bg = Image.open(bgfile) - fg = Image.open(fgfile) + bg = None + fg = None + mask = None + try: + bg = Image.open(bgfile) + fg = Image.open(fgfile) + except IOError: + pass if not bg or not fg: log.warning("Can't open avatar foreground and/or background image!") return None + if maskfile is not None: + try: + mask = Image.open(maskfile) + log.info('Mask image is {}'.format(maskfile)) + except IOError: + pass cutoff = float(bg.width) / 1.5 # Get provided image. @@ -195,6 +208,8 @@ class Bling(object): height = math.floor(image.height * (float(fg.height) / cutoff)) bg.thumbnail((width, height)) fg.thumbnail((width, height)) + if mask is not None: + mask.thumbnail((width, height)) # Pad with blank pixels. padded = Image.new(bg.mode, fg.size) @@ -202,16 +217,18 @@ class Bling(object): top = math.floor((padded.height - image.height) / 2) padded.paste(image, (left, top, left + image.width, top + image.height)) - # Ensure the user's image doesn't extend outside the foreground. - try: - r, g, b, a = bg.split() - if a is not None: - padded.putalpha(a) - except ValueError: - pass - # Merge them. result = Image.alpha_composite(Image.alpha_composite(bg, padded), fg) + + # Ensure the user's image doesn't extend outside the foreground. + if mask is not None: + try: + r, g, b, a = mask.split() + if a is not None: + result.putalpha(a) + except ValueError: + pass + b = io.BytesIO() result.save(b, 'PNG') return b.getvalue() -- 2.7.4