Detect and conserve identical images in nymph.

This commit is contained in:
Max Goodman
2011-12-06 17:17:26 -08:00
parent 733d5825c0
commit 5cb19c96d3

View File

@@ -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)