#!/usr/bin/env python
#
# imgindex.py
# Revision:  1.2
# Rev Date:  24 Mar 2001
#
# $Id: imgindex.py,v 1.3 2001/03/24 15:24:10 dyork Exp $
#
# This python program is designed to create an web page (HTML file)
# showing an index of the graphic files in a given directory.
#
# It was created out of frustration while trying to figure
# out what was on all the floppies I was generating with my
# Sony Mavica camera.  Hopefully it will save you some frustration...
#
# If you have any comments about this script, or if you
# make an improved version, please contact Dan York at
# dyork@Lodestar2.com
#
# Copyright (C) 1998-2001  Dan York, dyork@Lodestar2.com
# http://www.Lodestar2.com/software/imgindex/
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# http://www.gnu.org/copyleft/gpl.html
# ----------------------------------------------------------
#
# USAGE
#
# If used alone without any command-line arguments, the program
# will look in the current directory, find any files ending in
# .jpg, .JPG, .jpeg and .JPEG and create a file "index.html".
# The thumbnail images will be 320 pixels wide and 240 pixels
# high. (Note that the thumbnails are accomplished by using
# the HTML "height" and "width" attributes of the <IMG> tag
# and NOT by modifying files, therefore there is no reduction
# in the file size of the images.)
#
# It has the following command-line options:
#
#       -a            - index all formats (GIF, JPG and PNG) 
#       -c <columns>  - set the number of columns
#       -f <filename> - output filename
#       -h <height>   - height of images in HTML file
#       -t "title"    - title for use in text and HTML <TITLE>
#       -w <width>    - width of images in HTML file
#       -?            - print this help message
#
# Here are some examples (note that the order of the options
# does not matter):
#
#  imgindex.py -f mypics.html -w 640 -h 480 -a -t "My Pictures"
#  imgindex.py -a -w 128 -h 96 -c 4 -t "Very small pictures"
#
# ----------------------------------------------------------
# BUGS
#
# - When sorting, it does a straight ASCII sort and thus 
#   uppercase letters come first.
#
# ----------------------------------------------------------

from glob import glob
from sys import argv,stderr,exit
import time
import getopt

#
# Added this "uniq" function because the Windows version of 'glob' 
# seems to generate duplicate entries.  This function ensures that
# only 1 instance of each filename exists.
#
def uniq(list):
   ulist = []
   for i in list:
     if i not in ulist:
        ulist.append(i)
   return ulist

#
# Start the main function that performs the action
#
def filecreate(outfilename, width, height, targets, title, numcols):

    # open the file for writing
    try:
       outfile=open(outfilename,'w')
    except:
       print "\n\n***ERROR opening file '"+outfilename+"' for writing!\n\n"

    PrintHeader(outfile, title)

    # initialize the count of images to 0
    count = 0

    filelist = []

    # create the list of filenames
    for t in targets:
        filelist = filelist + glob('*.' + t)

    # sort that list alphabetically - note that currently uppercase
    # letters appear *before* lowercase letters
    filelist.sort()

    # Write out an entry in the table for each image.
    # Note that image "thumbnails" are provided purely by specifying
    # "height" and "width" attributes to the HTML <img> tag and *NOT*
    # by doing any actual image manipulation (so there is no reduction
    # in the actual filesize
    #
    for fname in (uniq(filelist)):
        # write out <tr> before every row of images (based on num of columns)
        if count == 0 or not (count % int(numcols)) : 
            outfile.write("<TR>\n")

        count = count + 1

        outfile.write("<TD>\n")
        outfile.write('<A HREF="'+fname+'"><IMG SRC="'+fname+\
	'" ALT="' + fname + '" WIDTH="'+ str(width) + \
	'" HEIGHT="'+ str(height)+ '"><BR>'+fname+"</A>\n")
  

    PrintFooter(outfile)

    print "\n"+outfilename+" written with "+str(count)+" images.\n"

def PrintHeader(fname,title):

    header = """<HTML>
<!-- 
  Created by imgindex.py - http://www.lodestar2.com/software/imgindex/
  Date generated: """+time.ctime(time.time())+\
    """
-->
<HEAD>
<TITLE>""" + title + """</TITLE>
<META name="GENERATOR" content="imgindex.py v 1.1">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000099">

<H1>""" + title +"""</H1>

<P>
<TABLE WIDTH="100%">
"""
    fname.write(header)
    
def PrintFooter(fname):
    fname.write ("</TABLE>\n</BODY>\n</HTML>\n")

def PrintHelp():
    """Help routine."""
    print """
    imgindex is a program to generate a web page with 'thumbnail' images
    of all the image files located in the current directory.

     Command-line options:
       -f <filename> - output filename
       -w <width>  - width of images in HTML file
       -h <height> - height of images in HTML file
       -c <columns>- the number of columns in the resulting file
       -a          - index all formats (GIF, JPG and PNG) instead of just JPG
       -t "title"  - title for use in text and HTML <TITLE>
       -?          - print this help message
    """


def main():
    """Main routine"""
    #
    # Set defaults
    #
    width = 320
    height = 240
    fname = 'index.html'
    numcolumns = 2
    targets = ['jpg','JPG','jpeg','JPEG']
    title = 'Index of Images'

    try:
        opts, args = getopt.getopt(argv[1:],"a?f:h:w:t:c:")
    except getopt.error, msg:
        stderr.write("\nimgindex: commandline error: "+ msg +"\n\n")
	exit(1)

    for i in opts:
        if i[0] == '-h':
	    height = i[1]
        elif i[0] == '-w':
	    width = i[1]
        elif i[0] == '-f':
	    fname = i[1]
        elif i[0] == '-?':
	    PrintHelp()
	    exit(0)
        elif i[0] == '-a':
            targets = ['jpg','JPG','jpeg','JPEG','gif','GIF','png','PNG']
        elif i[0] == '-t':
	    title = i[1]
        elif i[0] == '-c':
	    numcolumns = i[1]

    try:
        filecreate(fname,width,height,targets,title,numcolumns)
    except:
        stderr.write("\nError creating output file.\n\n")

if __name__ == '__main__' :
    main()

