Move image thumbnailing code to helpers.

This commit is contained in:
voussoir 2018-04-28 20:33:05 -07:00
parent 41823394eb
commit 5bc2bbdacb
2 changed files with 34 additions and 26 deletions

View file

@ -151,6 +151,33 @@ def fit_into_bounds(image_width, image_height, frame_width, frame_height):
return (new_width, new_height) return (new_width, new_height)
def generate_image_thumbnail(filepath, width, height):
image = PIL.Image.open(filepath)
(width, height) = image.size
(new_width, new_height) = fit_into_bounds(
image_width=width,
image_height=height,
frame_width=width,
frame_height=height,
)
if new_width < width:
image = image.resize((new_width, new_height))
if image.mode == 'RGBA':
background = 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')
return image
def get_mimetype(filepath): def get_mimetype(filepath):
''' '''
Extension to mimetypes.guess_type which uses my Extension to mimetypes.guess_type which uses my

View file

@ -790,33 +790,14 @@ class Photo(ObjectBase):
if self.simple_mimetype == 'image': if self.simple_mimetype == 'image':
self.photodb.log.debug('Thumbnailing %s', self.real_path.absolute_path) self.photodb.log.debug('Thumbnailing %s', self.real_path.absolute_path)
try: try:
image = PIL.Image.open(self.real_path.absolute_path) image = helpers.generate_image_thumbnail(
self.real_path.absolute_path,
width=self.photodb.config['thumbnail_width'],
height=self.photodb.config['thumbnail_height'],
)
except (OSError, ValueError): except (OSError, ValueError):
pass traceback.print_exc()
else: else:
(width, height) = image.size
(new_width, new_height) = helpers.fit_into_bounds(
image_width=width,
image_height=height,
frame_width=self.photodb.config['thumbnail_width'],
frame_height=self.photodb.config['thumbnail_height'],
)
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.absolute_path, quality=50) image.save(hopeful_filepath.absolute_path, quality=50)
return_filepath = hopeful_filepath return_filepath = hopeful_filepath