def thumb(self, resource, width, height, prefix, crop_type, options, preserve_orientation=False): """ Generate a thumbnail for the given image """ name = os.path.basename(resource.get_relative_deploy_path()) # don't make thumbnails for thumbnails if name.startswith(prefix): return # Prepare path, make all thumnails in single place(content/.thumbnails) # for simple maintenance but keep original deploy path to preserve # naming logic in generated site path = os.path.join(".thumbnails", os.path.dirname(resource.get_relative_deploy_path()), "%s%s" % (prefix, name)) target = resource.site.config.content_root_path.child_file(path) res = self.site.content.add_resource(target) res.set_relative_deploy_path(res.get_relative_deploy_path().replace('.thumbnails/', '', 1)) target.parent.make() if os.path.exists(target.path) and os.path.getmtime(resource.path) <= os.path.getmtime(target.path): return self.logger.debug("Making thumbnail for [%s]" % resource) im = self.Image.open(resource.path) if im.mode != 'RGBA': im = im.convert('RGBA') format = im.format if preserve_orientation and im.size[1] > im.size[0]: width, height = height, width resize_width, resize_height = thumb_scale_size(im.size[0], im.size[1], width, height) self.logger.debug("Resize to: %d,%d" % (resize_width, resize_height)) im = im.resize((resize_width, resize_height), self.Image.ANTIALIAS) if width is not None and height is not None: shiftx = shifty = 0 if crop_type == "center": shiftx = (im.size[0] - width)/2 shifty = (im.size[1] - height)/2 elif crop_type == "bottomright": shiftx = (im.size[0] - width) shifty = (im.size[1] - height) im = im.crop((shiftx, shifty, width + shiftx, height + shifty)) im.load() im.save(target.path, **options)
def test_height_and_width_landscape(self): ow, oh = 200, 100 nw, nh = thumb_scale_size(ow, oh, 50, 50) assert nw == 100 assert nh == 50
def test_height_and_width_portrait(self): ow, oh = 100, 200 nw, nh = thumb_scale_size(ow, oh, 50, 50) assert nw == 50 assert nh == 100
def test_height_only_nonintegral(self): ow, oh = 105, 200 nw, nh = thumb_scale_size(ow, oh, None, 100) assert nw == 53 assert nh == 100
def test_height_only(self): ow, oh = 100, 200 nw, nh = thumb_scale_size(ow, oh, None, 100) assert nw == 50 assert nh == 100
def test_width_only_nonintegral(self): ow, oh = 100, 205 nw, nh = thumb_scale_size(ow, oh, 50, None) assert nw == 50 assert nh == 103
def test_width_only(self): ow, oh = 100, 200 nw, nh = thumb_scale_size(ow, oh, 50, None) assert nw == 50 assert nh == 100