From 5cb19c96d3aaed9a8914dfa26569664513e68d73 Mon Sep 17 00:00:00 2001 From: Max Goodman Date: Tue, 6 Dec 2011 17:17:26 -0800 Subject: [PATCH] Detect and conserve identical images in nymph. --- r2/r2/lib/nymph.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/r2/r2/lib/nymph.py b/r2/r2/lib/nymph.py index 3a796ae49..ed232e46e 100644 --- a/r2/r2/lib/nymph.py +++ b/r2/r2/lib/nymph.py @@ -22,6 +22,7 @@ import os import re +import hashlib import Image import subprocess @@ -44,10 +45,10 @@ def _extract_css_info(match): class SpritableImage(object): - def __init__(self, base_dir, filename, should_stretch=False): - self.filename = filename + def __init__(self, image, should_stretch=False): + self.image = image self.stretch = should_stretch - self.image = Image.open(os.path.join(base_dir, filename)) + self.filenames = [] @property def width(self): @@ -89,12 +90,17 @@ def _load_spritable_images(css_filename): continue image_filename, should_stretch = _extract_css_info(m) + image = Image.open(os.path.join(css_location, image_filename)) + image_hash = hashlib.md5(image.convert("RGBA").tostring()).hexdigest() - if image_filename not in images: - images[image_filename] = SpritableImage(css_location, image_filename, should_stretch) + if image_hash not in images: + images[image_hash] = SpritableImage(image, should_stretch) else: - assert images[image_filename].stretch == should_stretch - return images.values() + assert images[image_hash].stretch == should_stretch + images[image_hash].filenames.append(image_filename) + + # Sort images by filename to group the layout by names when possible. + return sorted(images.values(), key=lambda i: i.filenames[0]) def _generate_sprite(images, sprite_path): @@ -149,7 +155,8 @@ def _rewrite_css(css_filename, sprite_path, images): # map filenames to coordinates locations = {} for image in images: - locations[image.filename] = image.sprite_location + for filename in image.filenames: + locations[filename] = image.sprite_location def rewrite_sprite_reference(match): image_filename, should_stretch = _extract_css_info(match)