Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Comparing changes

Choose two branches to see what's changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
base fork: industria/pyspritify
base: 9dea710f5d
...
head fork: industria/pyspritify
compare: 5a1ad80585
Checking mergeability… Don't worry, you can still create the pull request.
  • 6 commits
  • 1 file changed
  • 0 commit comments
  • 1 contributor
Showing with 41 additions and 36 deletions.
  1. +41 −36 spritify.py
View
77 spritify.py
@@ -46,7 +46,7 @@ def _setupOptionParser(self):
# Group for CSS options
cssGroup = OptionGroup(parser, "CSS options")
cssGroup.add_option("-c", "--css", dest="css", default="sprite.css", help="Name of the CSS file. (Default: sprite.css)")
- cssGroup.add_option("-n", "--classname", dest="classname", default=".sprite", help="Name of the CSS class defining the background url. (Default: .sprite)")
+ cssGroup.add_option("-n", "--classname", dest="classname", default="sprite", help="Name of the CSS class defining the background url. Don't prefix the classname with a period that is done by the CSS writer. (Default: sprite)")
cssGroup.add_option("-p", "--cssimagepath", dest="cssimagepath", default="", help="Path to prefix the sprite name with in the background-image url. Should be used if the sprite and CSS files are not written to the same directory.")
parser.add_option_group(cssGroup)
# Group for sprite options
@@ -76,14 +76,13 @@ def _parseArguments(self, parser):
else:
arg_dir = os.path.abspath(arguments[0])
if not os.path.isdir(arg_dir):
- parser.error("%s is not a directory" % (arg_dir))
+ parser.error(str.format("{0} is not a directory", arg_dir))
self.directory = arg_dir
# Check for image files in the directory and fail with parse error if no
# image files where found in the directory tree.
self.imagefiles = self._imagefiles(arg_dir)
if(0 == len(self.imagefiles)):
- parser.error("Directory %s doesn't contain any image files" % (self.directory))
- pass
+ parser.error(str.format("No image files found in {0}", self.directory))
def _imagefiles(self, directory):
@@ -111,20 +110,18 @@ class SpriteImage(object):
"""
def __init__(self, image, filename):
"""
- Initialize a SpriteImage object.
-
- image : PIL image.
- filename : Full path filename to the image.
+ Initialize a SpriteImage with a PIL image and
+ the full path filename of the PIL image.
"""
- self._image = image
- (self.width, self.height) = self._image.size
+ self.image = image
+ (self.width, self.height) = self.image.size
self.filename = filename
def __str__(self):
"""
String representation of a SprintImage.
"""
- return "%s width=%s height=%s" % (self.filename, self.width, self.height)
+ return str.format("{0} width={1} height={2}", self.filename, self.width, self.height)
class Spritify(object):
@@ -150,20 +147,18 @@ def _buildImageList(self, imagefilenames):
sprite_images.append(sprite_image)
except IOError as ioe:
if self.__conf.stop:
- print "Error: PIL failed to open [%s], with %s" % (f, ioe)
+ print str.format("Error: PIL failed to open [{0}], with {1}", f, ioe)
sys.exit(1);
else:
- print "Skipping file [%s], PIL error: %s" % (f, ioe)
+ print str.format("Skipping file [{0}], PIL error: {1}", f, ioe)
return sprite_images
def _virtualSpriteSize(self, images):
"""
Find the virtual sprite size, which is a sprite where either
- width or height is unlimited (that is sys.maxint) depending
- on with dimension has the largest size among the images.
-
- images : List of SpriteImages to the virtual sprite size from.
+ width or height is open-ended (sys.maxint) depending on
+ which dimension has the largest size among the images.
return: (width, height)
"""
width = 0
@@ -182,12 +177,6 @@ def _sortSpriteImages(self, images, width, height):
"""
Sort the sprite images according the the fixed dimension of the virtual
sprite size, which is basically the smallest dimension.
-
- images: List of SpriteImage objects to be sorted
- width: Virtual sprite width
- height: Virtual sprite height
-
- Return list of images sorted according to the dimensions of the virtual sprite size.
"""
if (width < height):
key_function = lambda sprite_image: sprite_image.width
@@ -202,11 +191,9 @@ def _layoutSprintImages(self, images):
depending on which is largest the other dimension will de unlimited in size
and the final height and width of the sprite will be determined when the layout
is complete.
-
- images: List of SpriteImage objects to layout
"""
(width, height) = self._virtualSpriteSize(images)
- print "Virtual sprite size %s x %s" % (width, height)
+ print str.format("Virtual sprite size {0} x {1}", width, height)
layout = Layout(width, height)
sorted_images = self._sortSpriteImages(images, width, height)
for image in sorted_images:
@@ -218,16 +205,15 @@ def _layoutSprintImages(self, images):
def _drawLayout(self, layout):
"""
- Draw an image from the layout.
+ Draw an image, the sprite, from a layout.
"""
(image_width, image_height) = layout.bounding()
print "Draw image: ", image_width, image_height
- sprint = Image.new("RGBA", (image_width, image_height))
-
+ sprite = Image.new("RGBA", (image_width, image_height))
for node in layout.nodes():
- sprint.paste(node.item._image, (node.x, node.y))
+ sprite.paste(node.item.image, (node.x, node.y))
print node
- sprint.save(self.__conf.spriteFilename, "PNG")
+ sprite.save(self.__conf.spriteFilename, "PNG")
def _spriteClassFromNode(self, node):
@@ -245,33 +231,52 @@ def _spriteClassFromNode(self, node):
def _writeCSS(self, layout):
"""
- Write the CSS for the layout.
+ Write CSS for the layout returning a list of classes in the file.
"""
css = open(self.__conf.cssfilename, "w")
# Register the image as background:url
url = self.__conf.cssimagepath + os.path.basename(self.__conf.spriteFilename)
- css.write(str.format("{0} {{background-image: url(\"{1}\");}}\n", self.__conf.cssClassname, url))
+ css.write(str.format(".{0} {{background-image: url(\"{1}\");}}\n", self.__conf.cssClassname, url))
# Register the images as classes by there filenames
+ cssClasses = []
for node in layout.nodes():
name = self._spriteClassFromNode(node)
+ cssClasses.append(name)
css.write(str.format(".{0} {{", name))
css.write(str.format("width: {0}px; height: {1}px; ", node.width, node.height))
css.write(str.format("background-position: {0}px {1}px;", 0 - node.x, 0 - node.y))
css.write("}\n");
css.close()
+ return cssClasses
+
+ def _writeHtml(self, cssClasses):
+ """
+ Write an overview HTML document referencing all classes added
+ to the CSS file written.
+ """
+ html = open("overview.html", "w")
+ html.write("<!DOCTYPE html><html><head><meta charset=\"utf-8\">")
+ html.write(str.format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" />", self.__conf.cssfilename))
+ html.write("</head><body>")
+ for cssClass in cssClasses:
+ html.write(str.format("<div class=\"{0} {1}\"></div>\n", self.__conf.cssClassname, cssClass))
+ html.write("""</body></html>""")
+ html.close()
+
def generate(self):
"""
Generate the sprite and CSS file
"""
- print "Traverse directory %s for images" % ( self.__conf.directory)
+ print str.format("Traverse directory {0} for images", self.__conf.directory)
print "Verbose output:", self.__conf.verbose
sprite_images = self._buildImageList(self.__conf.imagefiles)
layout = self._layoutSprintImages(sprite_images)
self._drawLayout(layout)
- self._writeCSS(layout)
-
+ cssClasses = self._writeCSS(layout)
+ print "Classes in the CSS", cssClasses
+ self._writeHtml(cssClasses)
if __name__ == '__main__':
conf = SpritifyConfiguration()

No commit comments for this range

Something went wrong with that request. Please try again.