XML technologies / XML / Python & XML / The Simple API for XML / Creating an image index
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
Online image libraries commonly use thumbnails linking to full-sized images, a convenient presentation many artists adopt for their work. Digital cameras and scanners have led more people to publish browsable image directories. Here we write Python taking a directory of images and thumbnails and producing an HTML index linking to full-sized images. The program saxthumbs.py expects an existing image/thumbnail directory and works on output from our earlier script index.py.
For saxthumbs.py to process thumbnails correctly, its SAX handler requires a naming convention, easily changed in code. Currently, in saxthumbs.py file is the expected XML element type, with a corresponding full image file <bildname>.jpg and thumbnail file t-<bildname>.jpg, where “t-” means thumbnail.
Generate an image list with index.py on a directory containing correctly named files:
$> ls -l *newimage*
-rw-rw-r-- 1 shm00 shm00 98197 Jan 18 11:08 newimage.jpg
-rw-rw-r-- 1 shm00 shm00 5272 Jan 18 11:42 t-newimage.jpgEach file ending in .jpg with a corresponding t-<bildname>.jpg is indexed; note the file-size difference.
Creating thumbnails
On Unix, prepare images easily using the command convert. It belongs to ImageMagick, installed by default by most Linux distributions. For other Unix systems, get it from ImageMagick: Convert, Edit, And Compose Images.
$> convert image.jpg –geometry 192x128 t-image.jpg This takes image.jpg at any size and creates a 192 × 128 pixel JPEG thumbnail. Windows bitmaps, with extension .bmp, can also be converted to JPEG with a second step:
$> convert image.bmp image.jpg
$> convert image.jpg –geometry 192x128 t-image.jpg Now that you understand convert, use a simple shell loop to produce thumbnails for every .jpg in the directory:
$> for each in *jpg
> do
> convert $each -geometry 192x128 t-$each
> echo $each
> doneYou should end up with something like this:
-rwxrwxr-x 1 shm00 shm00 97003 Jan 16 22:40 mvc-001s.jpg
-rwxrwxr-x 1 shm00 shm00 93373 Jan 16 22:40 mvc-002s.jpg
-rwxrwxr-x 1 shm00 shm00 86619 Jan 16 22:40 mvc-003s.jpg
-rwxrwxr-x 1 shm00 shm00 94894 Jan 16 22:40 mvc-004s.jpg
-rwxrwxr-x 1 shm00 shm00 76210 Jan 16 22:40 mvc-005s.jpg
-rwxrwxr-x 1 shm00 shm00 73704 Jan 16 22:40 mvc-006s.jpg
-rwxrwxr-x 1 shm00 shm00 80292 Jan 16 22:40 mvc-007s.jpg
-rw-rw-r-- 1 shm00 shm00 4434 Jan 21 11:46 t-mvc-001s.jpg
-rw-rw-r-- 1 shm00 shm00 4181 Jan 21 11:46 t-mvc-002s.jpg
-rw-rw-r-- 1 shm00 shm00 3604 Jan 21 11:46 t-mvc-003s.jpg
-rw-rw-r-- 1 shm00 shm00 4634 Jan 21 11:46 t-mvc-004s.jpg
-rw-rw-r-- 1 shm00 shm00 3339 Jan 21 11:46 t-mvc-005s.jpg
-rw-rw-r-- 1 shm00 shm00 2777 Jan 21 11:46 t-mvc-006s.jpg
-rw-rw-r-- 1 shm00 shm00 2996 Jan 21 11:46 t-mvc-007s.jpg This listing applies the program convert to mvc-00*.jpg files from a digital camera. The script saxthumbs.py marks up both thumbnails and individual images for display.
Running index.py on this directory creates an XML file used later when discussing saxthumbs.py:
$> ./index.py /home/shm00/images/ img.xml The new file, img.xml, contains file elements describing image files in a form suitable for the script.
Creating thumbnails on Windows
Without Unix or scriptable image software, create a directory on Windows yourself. Scale down originals, prefix thumbnails with t-, and ensure web images are JPEG, ending in .jpg. For example, open the folder My Pictures in Photoshop, resize each image to 192 × 128 pixels, and save a t- version of its original.
With this directory ready, run index.py to generate the XML image index.
Implementing the SAXThumbs handler
The SAXThumbs handler creates an anchor for each thumbnail in the HTML output and a separate HTML document showing each full-sized image. Finally, SAXThumbs produces one page of all thumbnails and one page per full-sized image.
The SAXThumbs handler subclasses ContentHandler. The thumbnail-index output filename is a command-line parameter passed to the constructor:
def __init__(self, thumbsFilename):
self.filename = thumbsFilename
def startDocument(self):
self.fd = open(self.filename, "w")
self.fd.write("<html><body>\n")
def endDocument(self):
self.fd.write("</body></html>\n")
self.fd.close( )Reaching the XML end means no images remain, so the thumbnail document is closed.
The remaining work happens in the method startElement. First, copy the filename without path information:
def startElement(self, name, attrs):
if name == "file":
filename = attrs.get("name", "")
# Extrahiere nur den Dateinamen
dir, localname = os.path.split(filename)
localname, ext = os.path.splitext(localname)Determine whether it is a thumbnail or full image. Thumbnails are wrapped in HTML anchors and added to the output:
if localname.startswith("t-") and ext == ".jpg":
# Erzeuge Anker-Tag in thumbs.html
fullImgLink = localname[2:] + ".html"
self.fd.write('<br><a href="%s"><img src="%s%s"></a>\n' % (fullImgLink, localname, ext))For a full image, create a separate HTML file showing it:
fullImageFile = os.path.join(dir, localname) + ".html"
print "Wird erzeugt:", fullImageFile
fullImageHTML = ('<html><body><img src="%s%s"></body></html>\n' % (localname, ext))
lfd = open(fullImageFile, "w")
lfd.write(fullImageHTML)
lfd.close( )Full-image HTML goes in the image’s directory. The thumbnail file goes where you run thumbmaker.py . The next example shows saxthumbs.py.
Example: saxthumbs.py
import os
from xml.sax import ContentHandler
class SAXThumbs(ContentHandler):
"""
Dies ist der SAX-Handler, der eine Darstellung des ganzen Bildes (eine .html-Seite)
für jede in der XML-Datei enthaltene Bilddatei erzeugt.
Er fügt auch einen Anker auf der Bildchenseite hinzu, der das Bildchen zeigt
und es mit der großen Bildseite verknüpft, die zuvor erzeugt wurde.
"""
def __init__(self, thumbsFilename):
self.filename = thumbsFilename
def startDocument(self):
self.fd = open(self.filename, "w")
self.fd.write("<html><body>\n")
def endDocument(self):
self.fd.write("</body></html>\n")
self.fd.close( )
def startElement(self, name, attrs):
if name == "file":
filename = attrs.get("name", "")
# Extrahiere nur den Dateinamen
dir, localname = os.path.split(filename)
localname, ext = os.path.splitext(localname)
if localname.startswith("t-") and ext == ".jpg":
# Erzeuge Anker-Tag in thumbs.html
fullImgLink = localname[2:] + ".html"
self.fd.write('<br><a href="%s"><img src="%s%s"></a>\n' % (fullImgLink, localname, ext))
fullImageFile = os.path.join(dir, localname[2:]) + ".html"
print "Wird erzeugt:", fullImageFile
fullImageHTML = ('<html><body><img src="%s%s"></body><html>\n' % (localname[2:], ext))
lfd = open(fullImageFile, "w")
lfd.write(fullImageHTML)
lfd.close( ) The file thumbmaker.py loads XML from standard input and registers the class SAXThumbs as the SAX handler. The next example shows the complete thumbmaker.py.
Example: thumbmaker.py
#!/usr/bin/env python
# thumbmaker.py
import sys
from xml.sax import make_parser
from saxthumbs import SAXThumbs
# Hauptprogramm
ch = SAXThumbs(sys.argv[1])
parser = make_parser( )
parser.setContentHandler(ch)
parser.parse(sys.stdin)Interestingly, this resembles our first script in art.py.
Before running thumbmaker.py, create the right image directory and run index.py on it to produce an XML file list. Then choose an index filename, such as mythumbs.html, and pass it to the script:
$> python thumbmaker.py mythumbs.html < img.xml Here, mythumbs.html is the output file and the XML source is img.xml.
Viewing thumbnails
After running thumbmaker.py, a thumbnail file exists in the working directory. Move it into the image directory:
$> mv mythumbs.html /home/shm00/tw/zero/images/
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de