Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a PIL decoder

I have a file which contains a single image of a specific format at a specific offset. I can already get a file-like for the embedded image which supports read(), seek(), and tell(). I want to take advantage of an existing PIL decoder to handle the embedded image, but be able to treat the entire file as an "image file" in its own right.

I have not been able to figure out how to do this given the documentation available and was wondering if anyone had any insights as to how I could do this.

like image 213
Ignacio Vazquez-Abrams Avatar asked Feb 13 '10 11:02

Ignacio Vazquez-Abrams


People also ask

Does PIL support TIF?

A list of images to append as additional frames. Each of the images in the list can be single or multiframe images. This is currently supported for GIF, PDF, PNG, TIFF, and WebP. It is also supported for ICO and ICNS.

Does PIL support JPEG?

PIL is a free library that adds image processing capabilities to your Python interpreter, supporting a range of image file formats such as PPM, PNG, JPEG, GIF, TIFF and BMP.

Does PIL support PDF?

As pointed out by @Kevin (see comment below) PIL has support for writing pdfs but not reading them. To read a pdf you will need some other library. You can look here which is a tutorial for handling PDFs with PyPDF2.

How do I view PIL images?

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. Image. show() Displays this image.


1 Answers

The relevant chapter of the docs is this one and I think it's fairly clear: if for example you want to decode image files in the new .zap-format, you write a ZapImagePlugin.py module which must perform a couple things:

  • have a class ZapImageFile(ImageFile.ImageFile): with string attributes format and format_description, and a hook-method def _open(self) (of which more later);
  • at module level, Image.register_open('zap', ZapImageFile) and Image.register_extension('ZAP', '.zap')

The specs for the _open method are very clearly laid out in the chapter -- it must read image data and metadata from open binary file-like object self.fp, raise SyntaxError (or another exception) ASAP if it detects that the file's not actually in the right format, set at least self.size and self.mode attributes, and in order to allow reading the image, also self.tile, a list of tile descriptors again in the format specified in that chapter (including the file-offset, which you say you know, and a decoder -- if the raw or bit decoders, documented in the chapter, don't meet your needs, the chapter recommends studying the sources of some of the many supplied decoders, such as JPEG, PNG, etc).

like image 153
Alex Martelli Avatar answered Oct 17 '22 03:10

Alex Martelli