degal/thumbnail.py
author Tero Marttila <terom@fixme.fi>
Sun, 14 Jun 2009 18:24:14 +0300
changeset 116 2d3721b9ffd0
parent 115 d5aa320697df
child 122 292aaba6d6ec
permissions -rw-r--r--
fix Thumbnail.size logic, s/if/elif/
"""
    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
        
        elif 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)