rename Image.pil_image -> Image.img, and shave off ~30ms per image by using Image.resize instead of Image.copy/Image.thumbnail
--- a/degal/commands/main.py Sun Jun 14 18:04:53 2009 +0300
+++ b/degal/commands/main.py Sun Jun 14 18:08:55 2009 +0300
@@ -43,7 +43,7 @@
# release large objects that are not needed anymore
# XXX: verify that this works
- del image.pil_image
+ del image.img
def render_folder_page (ctx, folder) :
"""
--- a/degal/image.py Sun Jun 14 18:04:53 2009 +0300
+++ b/degal/image.py Sun Jun 14 18:08:55 2009 +0300
@@ -38,13 +38,21 @@
self.description = None
@lazy_load
- def pil_image (self) :
+ def img (self) :
"""
Loads the image as a PIL.Image
"""
# open it up
return PIL.Image.open(self.path)
+
+ @property
+ def img_size (self) :
+ """
+ Returns the pixel (width, height) resolution tuple of this image.
+ """
+
+ return self.img.size
@lazy_load
def exif (self) :
@@ -76,7 +84,7 @@
stat = self.stat()
# XXX: avoid having to open the image?
- size = self.pil_image.size
+ size = self.img_size
# build
metadata = dict({
--- a/degal/thumbnail.py Sun Jun 14 18:04:53 2009 +0300
+++ b/degal/thumbnail.py Sun Jun 14 18:08:55 2009 +0300
@@ -11,12 +11,12 @@
A Thumbnail is a derivate of an Image, usually resized to some other size.
"""
- def __init__ (self, image, subdir, size) :
+ def __init__ (self, image, subdir, target_size) :
"""
Initialize to link against the given `image`.
`subdir` specifies the directory to store this thumbnail in.
- `size` determines the target resolution of the output thumbnail.
+ `target_size` determines the target resolution of the output thumbnail.
"""
# our file path, image name inside of the given subdir
@@ -24,7 +24,7 @@
# store
self.image = image
- self.size = size
+ self.target_size = target_size
def stale (self) :
"""
@@ -38,18 +38,40 @@
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
+ Render new output thumbnail.
"""
-
- # load a copy of the PIL.Image, as .thumbnail mutates it
- thumb = self.image.pil_image.copy()
- # resample to given size
- thumb.thumbnail(self.size, resample=True)
+ # create resized copy of main image, using our size
+ thumb = self.image.img.resize(self.size, resample=PIL.Image.ANTIALIAS)
- # and write out
+ # write it out
thumb.save(self.path)