[PYTHON IMAGE-SIG] How to write image files from an ImagePlugin

Fredrik Lundh fredrik_lundh@ivab.se
Thu, 28 Mar 1996 22:08:31 +0100

> For the time being the module will only read files (since I didn't
> understand how the plugin architecture works for writing. Fredrik?).

Quite simple, actually.  The _save function is called with an Image
object, an opened file handle, and a filename.

Your plugin should write the image to the file indicated by filename
(or to the file handle, if that suits you better).

But to make this work with the save method in the Image class, you
need to register your driver.  The following does this for the PPM

Image.register_save("PBM", _save)
Image.register_extension("PBM", ".pbm")
Image.register_extension("PBM", ".pgm")
Image.register_extension("PBM", ".ppm")

This means that we register a save handler named "PBM", and associates
the extensions pbm, pgm, and ppm with this driver.

Since you can handle multiple file formats with the Img driver, you
have to extend this scheme to be able to figure out what the user
really wants.

1. Create one save handler for each file format you can handle.  It
may be practical to let all these call a common routine that does the
actual work.

	def _save_tiff(im, fp, filename):
	    _save(im, fp, filename, "TIFF")

	def _save_sgi(im, fp, filename):
	    _save(im, fp, filename, "SGI")

2. Register these handlers under unique names:

	Image.register_save("TIFF", _save_tiff)
	Image.register_save("SGI", _save_sgi)

3. Register the appropriate extensions (see the handbook for the full
set of extensions for tiff and jpeg files), to allow a user to give
only a filename when saving a file:

	Image.register_extension("TIFF", ".tif")
	Image.register_extension("TIFF", ".tiff")
	Image.register_extension("SGI", ".sgi")
	Image.register_extension("SGI", ".rgb")

If a format is not explicitly given to the save method, PIL uses the
extension table to determine which format to use.

There's currently no mechanism to mediate between different drivers
that claims to be handling the same file format.  Last one loaded will
override the others.  Not really sure how to address this...

BTW, I've renamed the ImgImagePlugin.py to ImgExtImagePlugin.py since
there happens to be a file format named img as well...  Might need to
add some additional naming conventions for extensions other than file
formats, but let's leave that for another day.


IMAGE-SIG - SIG on Image Processing with Python

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