From edc2ae27682e7cd0a8908a139fdb103e0bb07cdc Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Sat, 4 Mar 2017 19:27:03 -0800 Subject: [PATCH] Give thumbnails a checkerboard bg for transparent images --- etiquette/helpers.py | 12 ++++++++++++ etiquette/objects.py | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/etiquette/helpers.py b/etiquette/helpers.py index 0b70e81..d2273f8 100644 --- a/etiquette/helpers.py +++ b/etiquette/helpers.py @@ -2,6 +2,7 @@ import datetime import math import mimetypes import os +import PIL.Image from . import constants from . import exceptions @@ -68,6 +69,17 @@ def binding_filler(column_names, values, require_all=True): bindings = [values[column] for column in column_names] return (qmarks, bindings) +def checkerboard_image(color_1, color_2, image_size, checker_size): + image = PIL.Image.new('RGB', image_size, color_1) + checker = PIL.Image.new('RGB', (checker_size, checker_size), color_2) + offset = True + for y in range(0, image_size[1], checker_size): + for x in range(0, image_size[0], checker_size * 2): + x += offset * checker_size + image.paste(checker, (x, y)) + offset = not offset + return image + def chunk_sequence(sequence, chunk_length, allow_incomplete=True): ''' Given a sequence, divide it into sequences of length `chunk_length`. diff --git a/etiquette/objects.py b/etiquette/objects.py index 9a2b4d8..c26d70f 100644 --- a/etiquette/objects.py +++ b/etiquette/objects.py @@ -506,7 +506,6 @@ class Photo(ObjectBase): self.photodb.log.debug('Thumbnailing %s' % self.real_filepath) try: image = PIL.Image.open(self.real_filepath) - image = image.convert('RGB') except (OSError, ValueError): pass else: @@ -519,6 +518,20 @@ class Photo(ObjectBase): ) if new_width < width: image = image.resize((new_width, new_height)) + + if image.mode == 'RGBA': + background = helpers.checkerboard_image( + color_1=(256, 256, 256), + color_2=(128, 128, 128), + image_size=image.size, + checker_size=8, + ) + # Thanks Yuji Tomita + # http://stackoverflow.com/a/9459208 + background.paste(image, mask=image.split()[3]) + image = background + + image = image.convert('RGB') image.save(hopeful_filepath, quality=50) return_filepath = hopeful_filepath