[PYTHON IMAGE-SIG] Re: [PIL] How to write compressed TIFF images

Fredrik Lundh fredrik.lundh@image.combitech.se
Tue, 13 May 1997 17:26:44 +0200

> an hour ago I wanted to show (to my boss) how easy
> it is to do some image manipulation in Python. He
> was quite impressed until I tried to write the
> resulting TIFF image to a file with G4 compression.

> Is it really so? Can't the tiff library be used for
> this?

Sure, it only takes someone to do it.  And an integrated G4 codec is
in the plans for 0.4 or something, but while you're waiting, here's
some simple code that uses the "tiffcp" utility to write TIFF's of all
flavours.  Just import the following module from your program, and you
can then use the "compression" option with the save method as shown in
the test snippet.

Cheers	/F

# use "tiffcp" to write compressed TIFF files.
# fredrik lundh (may 13, 1997)

import os, tempfile

# install standard driver
import Image, TiffImagePlugin 

LZW      = "lzw"
ZIP      = "zip"
JPEG     = "jpeg"
PACKBITS = "packbits"
G3       = "g3"
G4       = "g4"

def _save(im, fp, filename):

    # check compression mode
	compression = im.encoderinfo["compression"]
    except KeyError:
	# use standard driver
	TiffImagePlugin._save(im, fp, filename)
	# compress via temporary file
	if compression not in (LZW, ZIP, JPEG, PACKBITS, G3, G4):
	    raise IOError, "unknown compression mode"
	file = tempfile.mktemp()
	im.save(file, "TIFF")
	os.system("tiffcp -c %s %s %s" % (compression, file, filename))
	try: os.unlink(file)
	except: pass

Image.register_save(TiffImagePlugin.TiffImageFile.format, _save)

if __name__ == "__main__":
    # test
    im = Image.open("/usr/iv/tip/images/lenna.ppm")
    im = im.point(lambda v: v >= 128 and 255, "1")
    im.save("lenna.tif", compression=G4)

IMAGE-SIG - SIG on Image Processing with Python

send messages to: image-sig@python.org
administrivia to: image-sig-request@python.org