#! /usr/bin/python

# Copyright (C) 2000 Intevation GmbH <intevation@intevation.de>
# Author: Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the LGPL (>=v2)
# Read the file COPYING coming with MapIt! for details.

import os, sys, glob
import PIL.Image

"""Usage: imgconv file[, file...]

Convert all files to BMP files. 

"""

def convert_files(files, newext, format, **convparams):
    """Load images from the files in files and save them in the new
    format format. In between, convert the images according to
    convparams which are simply passed through to image.convert()
    """
    for file in files:
        basename, ext = os.path.splitext(file)
        newfile = basename + newext
        print "processing %s" % file,
        sys.stdout.flush()
        image = PIL.Image.open(file)
        image = apply(image.convert, (), convparams)
        print "writing %s" % newfile
        image.save(newfile, format)

def glob_files(files):
    result = []
    for file in files:
        result = result + glob.glob(file)
    return result

def main():
    files = sys.argv[1:]
    # on windows you might want to glob files:
    files = glob_files(files)
    convert_files(files, '.bmp', "BMP",
                  mode = 'P', palette = PIL.Image.ADAPTIVE)

main()
