rename Image.pil_image -> Image.img, and shave off ~30ms per image by using Image.resize instead of Image.copy/Image.thumbnail
"""
State for thumbnails; derivates of Images
"""
import filesystem
import PIL.Image
class Thumbnail (filesystem.File) :
"""
A Thumbnail is a derivate of an Image, usually resized to some other size.
"""
def __init__ (self, image, subdir, target_size) :
"""
Initialize to link against the given `image`.
`subdir` specifies the directory to store this thumbnail in.
`target_size` determines the target resolution of the output thumbnail.
"""
# our file path, image name inside of the given subdir
super(Thumbnail, self).__init__(subdir, image.fsname)
# store
self.image = image
self.target_size = target_size
def stale (self) :
"""
Tests if this thumbnail is stale
"""
if self.image.older_than(self) :
# both exist and this is newer
return False
else :
# this thumb doesn't exist or is older
return True
@property
def size (self) :
"""
Compute the *real* size of this thumbnail, from the image's actual size and our target size.
Preserves the aspect ratio etc.
"""
# real image size
img_width, img_height = self.image.img_size
# target size
thumb_width, thumb_height = self.target_size
# calc new size, preserving aspect ratio
if img_width > thumb_width :
height = max(img_height * thumb_width / img_width, 1)
width = thumb_width
if img_height > thumb_height :
width = max(img_width * thumb_height / img_height, 1)
height = thumb_height
return width, height
def update (self) :
"""
Render new output thumbnail.
"""
# create resized copy of main image, using our size
thumb = self.image.img.resize(self.size, resample=PIL.Image.ANTIALIAS)
# write it out
thumb.save(self.path)