ImageFile Module

The ImageFile module provides support functions for the image openand save functions.

In addition, it provides a Parser class which can be used to decodean image piece by piece (e.g. while receiving it over a network connection).This class implements the same consumer interface as the standard sgmlliband xmllib modules.

Example: Parse an image

  1. from PIL import ImageFile
  2.  
  3. fp = open("hopper.pgm", "rb")
  4.  
  5. p = ImageFile.Parser()
  6.  
  7. while 1:
  8. s = fp.read(1024)
  9. if not s:
  10. break
  11. p.feed(s)
  12.  
  13. im = p.close()
  14.  
  15. im.save("copy.jpg")

Parser

  • class PIL.ImageFile.Parser[source]
  • Incremental image parser. This class implements the standardfeed/close consumer interface.

    • close()[source]
    • (Consumer) Close the stream.

Returns:An image object.Raises:IOError – If the parser failed to parse the image file eitherbecause it cannot be identified or cannot bedecoded.

  • feed(data)[source]
  • (Consumer) Feed data to the parser.

Parameters:data – A string buffer.Raises:IOError – If the parser failed to parse the image file.

  • reset()[source]
  • (Consumer) Reset the parser. Note that you can only call thismethod immediately after you’ve created a parser; parserinstances cannot be reused.

PyDecoder

  • class PIL.ImageFile.PyDecoder[source]
  • Python implementation of a format decoder. Override this class andadd the decoding logic in the decode method.

See Writing Your Own File Decoder in Python

  • cleanup()[source]
  • Override to perform decoder specific cleanup

Returns:None

  • decode(buffer)[source]
  • Override to perform the decoding process.

Parameters:buffer – A bytes object with the data to be decoded.Returns:A tuple of (bytes consumed, errcode).If finished with decoding return <0 for the bytes consumed.Err codes are from ERRORS

  • init(args)[source]
  • Override to perform decoder specific initialization

Parameters:args – Array of args items from the tile entryReturns:None

  • setas_raw(_data, rawmode=None)[source]
  • Convenience method to set the internal image from a stream of raw data

Parameters:

  1. - **data** Bytes to be set
  2. - **rawmode** The rawmode to be used for the decoder.If not specified, it will default to the mode of the imageReturns:

None

  • setfd(fd)[source]
  • Called from ImageFile to set the python file-like object

Parameters:fd – A python file-like objectReturns:None

  • setimage(im, extents=None)[source]
  • Called from ImageFile to set the core output image for the decoder

Parameters:

  1. - **im** A core image object
  2. - **extents** a 4 tuple of (x0, y0, x1, y1) defining the rectanglefor this tileReturns:

None