home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / xbmc-9.11.exe / scripts / AppleMovieTrailers / resources / lib / PIL / Image.py < prev    next >
Encoding:
Python Source  |  2008-08-06  |  61.2 KB  |  1,924 lines

  1. #
  2. # The Python Imaging Library.
  3. # $Id: Image.py 2337 2005-03-25 07:50:30Z fredrik $
  4. #
  5. # the Image class wrapper
  6. #
  7. # partial release history:
  8. # 1995-09-09 fl   Created
  9. # 1996-03-11 fl   PIL release 0.0 (proof of concept)
  10. # 1996-04-30 fl   PIL release 0.1b1
  11. # 1999-07-28 fl   PIL release 1.0 final
  12. # 2000-06-07 fl   PIL release 1.1
  13. # 2000-10-20 fl   PIL release 1.1.1
  14. # 2001-05-07 fl   PIL release 1.1.2
  15. # 2002-03-15 fl   PIL release 1.1.3
  16. # 2003-05-10 fl   PIL release 1.1.4
  17. # 2005-03-28 fl   PIL release 1.1.5
  18. #
  19. # Copyright (c) 1997-2005 by Secret Labs AB.  All rights reserved.
  20. # Copyright (c) 1995-2005 by Fredrik Lundh.
  21. #
  22. # See the README file for information on usage and redistribution.
  23. #
  24.  
  25. VERSION = "1.1.5"
  26.  
  27. try:
  28.     import warnings
  29. except ImportError:
  30.     warnings = None
  31.  
  32. class _imaging_not_installed:
  33.     # module placeholder
  34.     def __getattr__(self, id):
  35.         raise ImportError("The _imaging C module is not installed")
  36.  
  37. try:
  38.     # give Tk a chance to set up the environment, in case we're
  39.     # using an _imaging module linked against libtcl/libtk (use
  40.     # __import__ to hide this from naive packagers; we don't really
  41.     # depend on Tk unless ImageTk is used, and that module already
  42.     # imports Tkinter)
  43.     __import__("FixTk")
  44. except ImportError:
  45.     pass
  46.  
  47. try:
  48.     # If the _imaging C module is not present, you can still use
  49.     # the "open" function to identify files, but you cannot load
  50.     # them.  Note that other modules should not refer to _imaging
  51.     # directly; import Image and use the Image.core variable instead.
  52.     import _imaging
  53.     core = _imaging
  54.     del _imaging
  55. except ImportError, v:
  56.     core = _imaging_not_installed()
  57.     if str(v)[:20] == "Module use of python" and warnings:
  58.         # The _imaging C module is present, but not compiled for
  59.         # the right version (windows only).  Print a warning, if
  60.         # possible.
  61.         warnings.warn(
  62.             "The _imaging extension was built for another version "
  63.             "of Python; most PIL functions will be disabled",
  64.             RuntimeWarning
  65.             )
  66.  
  67. import ImagePalette
  68. import os, string, sys
  69.  
  70. # type stuff
  71. from types import IntType, StringType, TupleType
  72.  
  73. try:
  74.     UnicodeStringType = type(unicode(""))
  75.     ##
  76.     # (Internal) Checks if an object is a string.  If the current
  77.     # Python version supports Unicode, this checks for both 8-bit
  78.     # and Unicode strings.
  79.     def isStringType(t):
  80.         return isinstance(t, StringType) or isinstance(t, UnicodeStringType)
  81. except NameError:
  82.     def isStringType(t):
  83.         return isinstance(t, StringType)
  84.  
  85. ##
  86. # (Internal) Checks if an object is a tuple.
  87.  
  88. def isTupleType(t):
  89.     return isinstance(t, TupleType)
  90.  
  91. ##
  92. # (Internal) Checks if an object is an image object.
  93.  
  94. def isImageType(t):
  95.     return hasattr(t, "im")
  96.  
  97. ##
  98. # (Internal) Checks if an object is a string, and that it points to a
  99. # directory.
  100.  
  101. def isDirectory(f):
  102.     return isStringType(f) and os.path.isdir(f)
  103.  
  104. from operator import isNumberType, isSequenceType
  105.  
  106. #
  107. # Debug level
  108.  
  109. DEBUG = 0
  110.  
  111. #
  112. # Constants (also defined in _imagingmodule.c!)
  113.  
  114. NONE = 0
  115.  
  116. # transpose
  117. FLIP_LEFT_RIGHT = 0
  118. FLIP_TOP_BOTTOM = 1
  119. ROTATE_90 = 2
  120. ROTATE_180 = 3
  121. ROTATE_270 = 4
  122.  
  123. # transforms
  124. AFFINE = 0
  125. EXTENT = 1
  126. PERSPECTIVE = 2
  127. QUAD = 3
  128. MESH = 4
  129.  
  130. # resampling filters
  131. NONE = 0
  132. NEAREST = 0
  133. ANTIALIAS = 1 # 3-lobed lanczos
  134. LINEAR = BILINEAR = 2
  135. CUBIC = BICUBIC = 3
  136.  
  137. # dithers
  138. NONE = 0
  139. NEAREST = 0
  140. ORDERED = 1 # Not yet implemented
  141. RASTERIZE = 2 # Not yet implemented
  142. FLOYDSTEINBERG = 3 # default
  143.  
  144. # palettes/quantizers
  145. WEB = 0
  146. ADAPTIVE = 1
  147.  
  148. # categories
  149. NORMAL = 0
  150. SEQUENCE = 1
  151. CONTAINER = 2
  152.  
  153. # --------------------------------------------------------------------
  154. # Registries
  155.  
  156. ID = []
  157. OPEN = {}
  158. MIME = {}
  159. SAVE = {}
  160. EXTENSION = {}
  161.  
  162. # --------------------------------------------------------------------
  163. # Modes supported by this version
  164.  
  165. _MODEINFO = {
  166.  
  167.     # official modes
  168.     "1": ("L", "L", ("1",)),
  169.     "L": ("L", "L", ("L",)),
  170.     "I": ("L", "I", ("I",)),
  171.     "F": ("L", "F", ("F",)),
  172.     "P": ("RGB", "L", ("P",)),
  173.     "RGB": ("RGB", "L", ("R", "G", "B")),
  174.     "RGBX": ("RGB", "L", ("R", "G", "B", "X")),
  175.     "RGBA": ("RGB", "L", ("R", "G", "B", "A")),
  176.     "CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
  177.     "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
  178.  
  179.     # Experimental modes include I;16, I;16B, RGBa, BGR;15,
  180.     # and BGR;24.  Use these modes only if you know exactly
  181.     # what you're doing...
  182.  
  183. }
  184.  
  185. MODES = _MODEINFO.keys()
  186. MODES.sort()
  187.  
  188. # raw modes that may be memory mapped.  NOTE: if you change this, you
  189. # may have to modify the stride calculation in map.c too!
  190. _MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16B")
  191.  
  192. ##
  193. # Gets the "base" mode for given mode.  This function returns "L" for
  194. # images that contain grayscale data, and "RGB" for images that
  195. # contain color data.
  196. #
  197. # @param mode Input mode.
  198. # @return "L" or "RGB".
  199. # @exception KeyError If the input mode was not a standard mode.
  200.  
  201. def getmodebase(mode):
  202.     # corresponding "base" mode (grayscale or colour)
  203.     if mode == "LA":
  204.         return "L"
  205.     if mode == "PA":
  206.         return "RGB"
  207.     return _MODEINFO[mode][0]
  208.  
  209. ##
  210. # Gets the storage type mode.  Given a mode, this function returns a
  211. # single-layer mode suitable for storing individual bands.
  212. #
  213. # @param mode Input mode.
  214. # @return "L", "I", or "F".
  215. # @exception KeyError If the input mode was not a standard mode.
  216.  
  217. def getmodetype(mode):
  218.     # storage type (per band)
  219.     if mode == "LA":
  220.         return "L"
  221.     if mode == "PA":
  222.         return "L"
  223.     return _MODEINFO[mode][1]
  224.  
  225. ##
  226. # Gets a list of individual band names.  Given a mode, this function
  227. # returns a tuple containing the names of individual bands (use
  228. # {@link #getmodetype} to get the mode used to store each individual
  229. # band.
  230. #
  231. # @param mode Input mode.
  232. # @return A tuple containing band names.  The length of the tuple
  233. #     gives the number of bands in an image of the given mode.
  234. # @exception KeyError If the input mode was not a standard mode.
  235.  
  236. def getmodebands(mode):
  237.     # return list of subcomponents
  238.     if mode == "LA":
  239.         return "L", "A"
  240.     if mode == "PA":
  241.         return "P", "A"
  242.     return len(_MODEINFO[mode][2])
  243.  
  244. # --------------------------------------------------------------------
  245. # Helpers
  246.  
  247. _initialized = 0
  248.  
  249. ##
  250. # Explicitly loads standard file format drivers.
  251.  
  252. def preinit():
  253.     "Load standard file format drivers."
  254.  
  255.     global _initialized
  256.     if _initialized >= 1:
  257.         return
  258.  
  259.     for m in ("Bmp", "Gif", "Jpeg", "Ppm", "Png", "Tiff"):
  260.         try:
  261.             __import__("%sImagePlugin" % m, globals(), locals(), [])
  262.         except ImportError:
  263.             pass # ignore missing driver for now
  264.  
  265.     _initialized = 1
  266.  
  267. ##
  268. # Explicitly initializes the Python Imaging Library.  This function
  269. # loads all available file format drivers.
  270.  
  271. def init():
  272.     "Load all file format drivers."
  273.  
  274.     global _initialized
  275.     if _initialized >= 2:
  276.         return
  277.  
  278.     visited = {}
  279.  
  280.     directories = sys.path
  281.  
  282.     try:
  283.         directories = directories + [os.path.dirname(__file__)]
  284.     except NameError:
  285.         pass
  286.  
  287.     # only check directories (including current, if present in the path)
  288.     for directory in filter(isDirectory, directories):
  289.         fullpath = os.path.abspath(directory)
  290.         if visited.has_key(fullpath):
  291.             continue
  292.         for file in os.listdir(directory):
  293.             if file[-14:] == "ImagePlugin.py":
  294.                 f, e = os.path.splitext(file)
  295.                 try:
  296.                     sys.path.insert(0, directory)
  297.                     try:
  298.                         __import__(f, globals(), locals(), [])
  299.                     finally:
  300.                         del sys.path[0]
  301.                 except ImportError:
  302.                     if DEBUG:
  303.                         print "Image: failed to import",
  304.                         print f, ":", sys.exc_value
  305.         visited[fullpath] = None
  306.  
  307.     if OPEN or SAVE:
  308.         _initialized = 2
  309.  
  310.  
  311. # --------------------------------------------------------------------
  312. # Codec factories (used by tostring/fromstring and ImageFile.load)
  313.  
  314. def _getdecoder(mode, decoder_name, args, extra=()):
  315.  
  316.     # tweak arguments
  317.     if args is None:
  318.         args = ()
  319.     elif not isTupleType(args):
  320.         args = (args,)
  321.  
  322.     try:
  323.         # get decoder
  324.         decoder = getattr(core, decoder_name + "_decoder")
  325.         # print decoder, (mode,) + args + extra
  326.         return apply(decoder, (mode,) + args + extra)
  327.     except AttributeError:
  328.         raise IOError("decoder %s not available" % decoder_name)
  329.  
  330. def _getencoder(mode, encoder_name, args, extra=()):
  331.  
  332.     # tweak arguments
  333.     if args is None:
  334.         args = ()
  335.     elif not isTupleType(args):
  336.         args = (args,)
  337.  
  338.     try:
  339.         # get encoder
  340.         encoder = getattr(core, encoder_name + "_encoder")
  341.         # print encoder, (mode,) + args + extra
  342.         return apply(encoder, (mode,) + args + extra)
  343.     except AttributeError:
  344.         raise IOError("encoder %s not available" % encoder_name)
  345.  
  346.  
  347. # --------------------------------------------------------------------
  348. # Simple expression analyzer
  349.  
  350. class _E:
  351.     def __init__(self, data): self.data = data
  352.     def __coerce__(self, other): return self, _E(other)
  353.     def __add__(self, other): return _E((self.data, "__add__", other.data))
  354.     def __mul__(self, other): return _E((self.data, "__mul__", other.data))
  355.  
  356. def _getscaleoffset(expr):
  357.     stub = ["stub"]
  358.     data = expr(_E(stub)).data
  359.     try:
  360.         (a, b, c) = data # simplified syntax
  361.         if (a is stub and b == "__mul__" and isNumberType(c)):
  362.             return c, 0.0
  363.         if (a is stub and b == "__add__" and isNumberType(c)):
  364.             return 1.0, c
  365.     except TypeError: pass
  366.     try:
  367.         ((a, b, c), d, e) = data # full syntax
  368.         if (a is stub and b == "__mul__" and isNumberType(c) and
  369.             d == "__add__" and isNumberType(e)):
  370.             return c, e
  371.     except TypeError: pass
  372.     raise ValueError("illegal expression")
  373.  
  374.  
  375. # --------------------------------------------------------------------
  376. # Implementation wrapper
  377.  
  378. ##
  379. # This class represents an image object.  To create Image objects, use
  380. # the appropriate factory functions.  There's hardly ever any reason
  381. # to call the Image constructor directly.
  382. #
  383. # @see #open
  384. # @see #new
  385. # @see #fromstring
  386.  
  387. class Image:
  388.  
  389.     format = None
  390.     format_description = None
  391.  
  392.     def __init__(self):
  393.         self.im = None
  394.         self.mode = ""
  395.         self.size = (0, 0)
  396.         self.palette = None
  397.         self.info = {}
  398.         self.category = NORMAL
  399.         self.readonly = 0
  400.  
  401.     def _new(self, im):
  402.         new = Image()
  403.         new.im = im
  404.         new.mode = im.mode
  405.         new.size = im.size
  406.         new.palette = self.palette
  407.         if im.mode == "P":
  408.             new.palette = ImagePalette.ImagePalette()
  409.         try:
  410.             new.info = self.info.copy()
  411.         except AttributeError:
  412.             # fallback (pre-1.5.2)
  413.             new.info = {}
  414.             for k, v in self.info:
  415.                 new.info[k] = v
  416.         return new
  417.  
  418.     _makeself = _new # compatibility
  419.  
  420.     def _copy(self):
  421.         self.load()
  422.         self.im = self.im.copy()
  423.         self.readonly = 0
  424.  
  425.     def _dump(self, file=None, format=None):
  426.         import tempfile
  427.         if not file:
  428.             file = tempfile.mktemp()
  429.         self.load()
  430.         if not format or format == "PPM":
  431.             self.im.save_ppm(file)
  432.         else:
  433.             file = file + "." + format
  434.             self.save(file, format)
  435.         return file
  436.  
  437.     ##
  438.     # Returns a string containing pixel data.
  439.     #
  440.     # @param encoder_name What encoder to use.  The default is to
  441.     #    use the standard "raw" encoder.
  442.     # @param *args Extra arguments to the encoder.
  443.     # @return An 8-bit string.
  444.  
  445.     def tostring(self, encoder_name="raw", *args):
  446.         "Return image as a binary string"
  447.  
  448.         # may pass tuple instead of argument list
  449.         if len(args) == 1 and isTupleType(args[0]):
  450.             args = args[0]
  451.  
  452.         if encoder_name == "raw" and args == ():
  453.             args = self.mode
  454.  
  455.         self.load()
  456.  
  457.         # unpack data
  458.         e = _getencoder(self.mode, encoder_name, args)
  459.         e.setimage(self.im)
  460.  
  461.         data = []
  462.         while 1:
  463.             l, s, d = e.encode(65536)
  464.             data.append(d)
  465.             if s:
  466.                 break
  467.         if s < 0:
  468.             raise RuntimeError("encoder error %d in tostring" % s)
  469.  
  470.         return string.join(data, "")
  471.  
  472.     ##
  473.     # Returns the image converted to an X11 bitmap.  This method
  474.     # only works for mode "1" images.
  475.     #
  476.     # @param name The name prefix to use for the bitmap variables.
  477.     # @return A string containing an X11 bitmap.
  478.     # @exception ValueError If the mode is not "1"
  479.  
  480.     def tobitmap(self, name="image"):
  481.         "Return image as an XBM bitmap"
  482.  
  483.         self.load()
  484.         if self.mode != "1":
  485.             raise ValueError("not a bitmap")
  486.         data = self.tostring("xbm")
  487.         return string.join(["#define %s_width %d\n" % (name, self.size[0]),
  488.                 "#define %s_height %d\n"% (name, self.size[1]),
  489.                 "static char %s_bits[] = {\n" % name, data, "};"], "")
  490.  
  491.     ##
  492.     # Loads this image with pixel data from a string.
  493.     # <p>
  494.     # This method is similar to the {@link #fromstring} function, but
  495.     # loads data into this image instead of creating a new image
  496.     # object.
  497.  
  498.     def fromstring(self, data, decoder_name="raw", *args):
  499.         "Load data to image from binary string"
  500.  
  501.         # may pass tuple instead of argument list
  502.         if len(args) == 1 and isTupleType(args[0]):
  503.             args = args[0]
  504.  
  505.         # default format
  506.         if decoder_name == "raw" and args == ():
  507.             args = self.mode
  508.  
  509.         # unpack data
  510.         d = _getdecoder(self.mode, decoder_name, args)
  511.         d.setimage(self.im)
  512.         s = d.decode(data)
  513.  
  514.         if s[0] >= 0:
  515.             raise ValueError("not enough image data")
  516.         if s[1] != 0:
  517.             raise ValueError("cannot decode image data")
  518.  
  519.     ##
  520.     # Allocates storage for the image and loads the pixel data.  In
  521.     # normal cases, you don't need to call this method, since the
  522.     # Image class automatically loads an opened image when it is
  523.     # accessed for the first time.
  524.  
  525.     def load(self):
  526.         "Explicitly load pixel data."
  527.         if self.im and self.palette and self.palette.dirty:
  528.             # realize palette
  529.             apply(self.im.putpalette, self.palette.getdata())
  530.             self.palette.dirty = 0
  531.             self.palette.mode = "RGB"
  532.             self.palette.rawmode = None
  533.             if self.info.has_key("transparency"):
  534.                 self.im.putpalettealpha(self.info["transparency"], 0)
  535.                 self.palette.mode = "RGBA"
  536.  
  537.     ##
  538.     # Verifies the contents of a file. For data read from a file, this
  539.     # method attempts to determine if the file is broken, without
  540.     # actually decoding the image data.  If this method finds any
  541.     # problems, it raises suitable exceptions.  If you need to load
  542.     # the image after using this method, you must reopen the image
  543.     # file.
  544.  
  545.     def verify(self):
  546.         "Verify file contents."
  547.         pass
  548.  
  549.  
  550.     ##
  551.     # Returns a converted copy of this image. For the "P" mode, this
  552.     # method translates pixels through the palette.  If mode is
  553.     # omitted, a mode is chosen so that all information in the image
  554.     # and the palette can be represented without a palette.
  555.     # <p>
  556.     # The current version supports all possible conversions between
  557.     # "L", "RGB" and "CMYK."
  558.     # <p>
  559.     # When translating a colour image to black and white (mode "L"),
  560.     # the library uses the ITU-R 601-2 luma transform:
  561.     # <p>
  562.     # <b>L = R * 299/1000 + G * 587/1000 + B * 114/1000</b>
  563.     # <p>
  564.     # When translating a greyscale image into a bilevel image (mode
  565.     # "1"), all non-zero values are set to 255 (white). To use other
  566.     # thresholds, use the {@link #Image.point} method.
  567.     #
  568.     # @def convert(mode, matrix=None)
  569.     # @param mode The requested mode.
  570.     # @param matrix An optional conversion matrix.  If given, this
  571.     #    should be 4- or 16-tuple containing floating point values.
  572.     # @return An Image object.
  573.  
  574.     def convert(self, mode=None, data=None, dither=None,
  575.                 palette=WEB, colors=256):
  576.         "Convert to other pixel format"
  577.  
  578.         if not mode:
  579.             # determine default mode
  580.             if self.mode == "P":
  581.                 self.load()
  582.                 if self.palette:
  583.                     mode = self.palette.mode
  584.                 else:
  585.                     mode = "RGB"
  586.             else:
  587.                 return self.copy()
  588.  
  589.         self.load()
  590.  
  591.         if data:
  592.             # matrix conversion
  593.             if mode not in ("L", "RGB"):
  594.                 raise ValueError("illegal conversion")
  595.             im = self.im.convert_matrix(mode, data)
  596.             return self._new(im)
  597.  
  598.         if mode == "P" and palette == ADAPTIVE:
  599.             im = self.im.quantize(colors)
  600.             return self._new(im)
  601.  
  602.         # colourspace conversion
  603.         if dither is None:
  604.             dither = FLOYDSTEINBERG
  605.  
  606.         try:
  607.             im = self.im.convert(mode, dither)
  608.         except ValueError:
  609.             try:
  610.                 # normalize source image and try again
  611.                 im = self.im.convert(getmodebase(self.mode))
  612.                 im = im.convert(mode, dither)
  613.             except KeyError:
  614.                 raise ValueError("illegal conversion")
  615.  
  616.         return self._new(im)
  617.  
  618.     def quantize(self, colors=256, method=0, kmeans=0, palette=None):
  619.  
  620.         # methods:
  621.         #    0 = median cut
  622.         #    1 = maximum coverage
  623.  
  624.         # NOTE: this functionality will be moved to the extended
  625.         # quantizer interface in a later version of PIL.
  626.  
  627.         self.load()
  628.  
  629.         if palette:
  630.             # use palette from reference image
  631.             palette.load()
  632.             if palette.mode != "P":
  633.                 raise ValueError("bad mode for palette image")
  634.             if self.mode != "RGB" and self.mode != "L":
  635.                 raise ValueError(
  636.                     "only RGB or L mode images can be quantized to a palette"
  637.                     )
  638.             im = self.im.convert("P", 1, palette.im)
  639.             return self._makeself(im)
  640.  
  641.         im = self.im.quantize(colors, method, kmeans)
  642.         return self._new(im)
  643.  
  644.     ##
  645.     # Copies this image. Use this method if you wish to paste things
  646.     # into an image, but still retain the original.
  647.     #
  648.     # @return An Image object.
  649.  
  650.     def copy(self):
  651.         "Copy raster data"
  652.  
  653.         self.load()
  654.         im = self.im.copy()
  655.         return self._new(im)
  656.  
  657.     ##
  658.     # Returns a rectangular region from this image. The box is a
  659.     # 4-tuple defining the left, upper, right, and lower pixel
  660.     # coordinate.
  661.     # <p>
  662.     # This is a lazy operation.  Changes to the source image may or
  663.     # may not be reflected in the cropped image.  To break the
  664.     # connection, call the {@link #Image.load} method on the cropped
  665.     # copy.
  666.     #
  667.     # @param The crop rectangle, as a (left, upper, right, lower)-tuple.
  668.     # @return An Image object.
  669.  
  670.     def crop(self, box=None):
  671.         "Crop region from image"
  672.  
  673.         self.load()
  674.         if box is None:
  675.             return self.copy()
  676.  
  677.         # lazy operation
  678.         return _ImageCrop(self, box)
  679.  
  680.     ##
  681.     # Configures the image file loader so it returns a version of the
  682.     # image that as closely as possible matches the given mode and
  683.     # size.  For example, you can use this method to convert a colour
  684.     # JPEG to greyscale while loading it, or to extract a 128x192
  685.     # version from a PCD file.
  686.     # <p>
  687.     # Note that this method modifies the Image object in place.  If
  688.     # the image has already been loaded, this method has no effect.
  689.     #
  690.     # @param mode The requested mode.
  691.     # @param size The requested size.
  692.  
  693.     def draft(self, mode, size):
  694.         "Configure image decoder"
  695.  
  696.         pass
  697.  
  698.     def _expand(self, xmargin, ymargin=None):
  699.         if ymargin is None:
  700.             ymargin = xmargin
  701.         self.load()
  702.         return self._new(self.im.expand(xmargin, ymargin, 0))
  703.  
  704.     ##
  705.     # Filters this image using the given filter.  For a list of
  706.     # available filters, see the <b>ImageFilter</b> module.
  707.     #
  708.     # @param filter Filter kernel.
  709.     # @return An Image object.
  710.     # @see ImageFilter
  711.  
  712.     def filter(self, filter):
  713.         "Apply environment filter to image"
  714.  
  715.         self.load()
  716.  
  717.         from ImageFilter import Filter
  718.         if not isinstance(filter, Filter):
  719.             filter = filter()
  720.  
  721.         if self.im.bands == 1:
  722.             return self._new(filter.filter(self.im))
  723.         # fix to handle multiband images since _imaging doesn't
  724.         ims = []
  725.         for c in range(self.im.bands):
  726.             ims.append(self._new(filter.filter(self.im.getband(c))))
  727.         return merge(self.mode, ims)
  728.  
  729.     ##
  730.     # Returns a tuple containing the name of each band in this image.
  731.     # For example, <b>getbands</b> on an RGB image returns ("R", "G", "B").
  732.     #
  733.     # @return A tuple containing band names.
  734.  
  735.     def getbands(self):
  736.         "Get band names"
  737.  
  738.         return _MODEINFO[self.mode][2]
  739.  
  740.     ##
  741.     # Calculates the bounding box of the non-zero regions in the
  742.     # image.
  743.     #
  744.     # @return The bounding box is returned as a 4-tuple defining the
  745.     #    left, upper, right, and lower pixel coordinate. If the image
  746.     #    is completely empty, this method returns None.
  747.  
  748.     def getbbox(self):
  749.         "Get bounding box of actual data (non-zero pixels) in image"
  750.  
  751.         self.load()
  752.         return self.im.getbbox()
  753.  
  754.     ##
  755.     # Returns a list of colors used in this image.
  756.     #
  757.     # @param maxcolors Maximum number of colors.  If this number is
  758.     #    exceeded, this method returns None.  The default limit is
  759.     #    256 colors.
  760.     # @return An unsorted list of (count, pixel) values.
  761.  
  762.     def getcolors(self, maxcolors=256):
  763.         "Get colors from image, up to given limit"
  764.  
  765.         self.load()
  766.         if self.mode in ("1", "L", "P"):
  767.             h = self.im.histogram()
  768.             out = []
  769.             for i in range(256):
  770.                 if h[i]:
  771.                     out.append((h[i], i))
  772.             if len(out) > maxcolors:
  773.                 return None
  774.             return out
  775.         return self.im.getcolors(maxcolors)
  776.  
  777.     ##
  778.     # Returns the contents of this image as a sequence object
  779.     # containing pixel values.  The sequence object is flattened, so
  780.     # that values for line one follow directly after the values of
  781.     # line zero, and so on.
  782.     # <p>
  783.     # Note that the sequence object returned by this method is an
  784.     # internal PIL data type, which only supports certain sequence
  785.     # operations.  To convert it to an ordinary sequence (e.g. for
  786.     # printing), use <b>list(im.getdata())</b>.
  787.     #
  788.     # @param band What band to return.  The default is to return
  789.     #    all bands.  To return a single band, pass in the index
  790.     #    value (e.g. 0 to get the "R" band from an "RGB" image).
  791.     # @return A sequence-like object.
  792.  
  793.     def getdata(self, band = None):
  794.         "Get image data as sequence object."
  795.  
  796.         self.load()
  797.         if band is not None:
  798.             return self.im.getband(band)
  799.         return self.im # could be abused
  800.  
  801.     ##
  802.     # Gets the the minimum and maximum pixel values for each band in
  803.     # the image.
  804.     #
  805.     # @return For a single-band image, a 2-tuple containing the
  806.     #    minimum and maximum pixel value.  For a multi-band image,
  807.     #    a tuple containing one 2-tuple for each band.
  808.  
  809.     def getextrema(self):
  810.         "Get min/max value"
  811.  
  812.         self.load()
  813.         if self.im.bands > 1:
  814.             extrema = []
  815.             for i in range(self.im.bands):
  816.                 extrema.append(self.im.getband(i).getextrema())
  817.             return tuple(extrema)
  818.         return self.im.getextrema()
  819.  
  820.     ##
  821.     # Returns a PyCObject that points to the internal image memory.
  822.     #
  823.     # @return A PyCObject object.
  824.  
  825.     def getim(self):
  826.         "Get PyCObject pointer to internal image memory"
  827.  
  828.         self.load()
  829.         return self.im.ptr
  830.  
  831.  
  832.     ##
  833.     # Returns the image palette as a list.
  834.     #
  835.     # @return A list of color values [r, g, b, ...], or None if the
  836.     #    image has no palette.
  837.  
  838.     def getpalette(self):
  839.         "Get palette contents."
  840.  
  841.         self.load()
  842.         try:
  843.             return map(ord, self.im.getpalette())
  844.         except ValueError:
  845.             return None # no palette
  846.  
  847.  
  848.     ##
  849.     # Returns the pixel value at a given position.
  850.     #
  851.     # @param xy The coordinate, given as (x, y).
  852.     # @return The pixel value.  If the image is a multi-layer image,
  853.     #    this method returns a tuple.
  854.  
  855.     def getpixel(self, xy):
  856.         "Get pixel value"
  857.  
  858.         self.load()
  859.         return self.im.getpixel(xy)
  860.  
  861.     ##
  862.     # Returns the horizontal and vertical projection.
  863.     #
  864.     # @return Two sequences, indicating where there are non-zero
  865.     #     pixels along the X-axis and the Y-axis, respectively.
  866.  
  867.     def getprojection(self):
  868.         "Get projection to x and y axes"
  869.  
  870.         self.load()
  871.         x, y = self.im.getprojection()
  872.         return map(ord, x), map(ord, y)
  873.  
  874.     ##
  875.     # Returns a histogram for the image. The histogram is returned as
  876.     # a list of pixel counts, one for each pixel value in the source
  877.     # image. If the image has more than one band, the histograms for
  878.     # all bands are concatenated (for example, the histogram for an
  879.     # "RGB" image contains 768 values).
  880.     # <p>
  881.     # A bilevel image (mode "1") is treated as a greyscale ("L") image
  882.     # by this method.
  883.     # <p>
  884.     # If a mask is provided, the method returns a histogram for those
  885.     # parts of the image where the mask image is non-zero. The mask
  886.     # image must have the same size as the image, and be either a
  887.     # bi-level image (mode "1") or a greyscale image ("L").
  888.     #
  889.     # @def histogram(mask=None)
  890.     # @param mask An optional mask.
  891.     # @return A list containing pixel counts.
  892.  
  893.     def histogram(self, mask=None, extrema=None):
  894.         "Take histogram of image"
  895.  
  896.         self.load()
  897.         if mask:
  898.             mask.load()
  899.             return self.im.histogram((0, 0), mask.im)
  900.         if self.mode in ("I", "F"):
  901.             if extrema is None:
  902.                 extrema = self.getextrema()
  903.             return self.im.histogram(extrema)
  904.         return self.im.histogram()
  905.  
  906.     ##
  907.     # (Deprecated) Returns a copy of the image where the data has been
  908.     # offset by the given distances. Data wraps around the edges. If
  909.     # yoffset is omitted, it is assumed to be equal to xoffset.
  910.     # <p>
  911.     # This method is deprecated. New code should use the <b>offset</b>
  912.     # function in the <b>ImageChops</b> module.
  913.     #
  914.     # @param xoffset The horizontal distance.
  915.     # @param yoffset The vertical distance.  If omitted, both
  916.     #    distances are set to the same value.
  917.     # @return An Image object.
  918.  
  919.     def offset(self, xoffset, yoffset=None):
  920.         "(deprecated) Offset image in horizontal and/or vertical direction"
  921.         if warnings:
  922.             warnings.warn(
  923.                 "'offset' is deprecated; use 'ImageChops.offset' instead",
  924.                DeprecationWarning
  925.                 )
  926.         import ImageChops
  927.         return ImageChops.offset(self, xoffset, yoffset)
  928.  
  929.     ##
  930.     # Pastes another image into this image. The box argument is either
  931.     # a 2-tuple giving the upper left corner, a 4-tuple defining the
  932.     # left, upper, right, and lower pixel coordinate, or None (same as
  933.     # (0, 0)).  If a 4-tuple is given, the size of the pasted image
  934.     # must match the size of the region.
  935.     # <p>
  936.     # If the modes don't match, the pasted image is converted to the
  937.     # mode of this image (see the {@link #Image.convert} method for
  938.     # details).
  939.     # <p>
  940.     # Instead of an image, the source can be a integer or tuple
  941.     # containing pixel values.  The method then fills the region
  942.     # with the given colour.  When creating RGB images, you can
  943.     # also use colour strings as supported by the ImageColor module.
  944.     # <p>
  945.     # If a mask is given, this method updates only the regions
  946.     # indicated by the mask.  You can use either "1", "L" or "RGBA"
  947.     # images (in the latter case, the alpha band is used as mask).
  948.     # Where the mask is 255, the given image is copied as is.  Where
  949.     # the mask is 0, the current value is preserved.  Intermediate
  950.     # values can be used for transparency effects.
  951.     # <p>
  952.     # Note that if you paste an "RGBA" image, the alpha band is
  953.     # ignored.  You can work around this by using the same image as
  954.     # both source image and mask.
  955.     #
  956.     # @param im Source image or pixel value (integer or tuple).
  957.     # @param box An optional 4-tuple giving the region to paste into.
  958.     #    If a 2-tuple is used instead, it's treated as the upper left
  959.     #    corner.  If omitted or None, the source is pasted into the
  960.     #    upper left corner.
  961.     #    <p>
  962.     #    If an image is given as the second argument and there is no
  963.     #    third, the box defaults to (0, 0), and the second argument
  964.     #    is interpreted as a mask image.
  965.     # @param mask An optional mask image.
  966.     # @return An Image object.
  967.  
  968.     def paste(self, im, box=None, mask=None):
  969.         "Paste other image into region"
  970.  
  971.         if isImageType(box) and mask is None:
  972.             # abbreviated paste(im, mask) syntax
  973.             mask = box; box = None
  974.  
  975.         if box is None:
  976.             # cover all of self
  977.             box = (0, 0) + self.size
  978.  
  979.         if len(box) == 2:
  980.             # lower left corner given; get size from image or mask
  981.             if isImageType(im):
  982.                 size = im.size
  983.             elif isImageType(mask):
  984.                 size = mask.size
  985.             else:
  986.                 # FIXME: use self.size here?
  987.                 raise ValueError(
  988.                     "cannot determine region size; use 4-item box"
  989.                     )
  990.             box = box + (box[0]+size[0], box[1]+size[1])
  991.  
  992.         if isStringType(im):
  993.             import ImageColor
  994.             im = ImageColor.getcolor(im, self.mode)
  995.  
  996.         elif isImageType(im):
  997.             im.load()
  998.             if self.mode != im.mode:
  999.                 if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
  1000.                     # should use an adapter for this!
  1001.                     im = im.convert(self.mode)
  1002.             im = im.im
  1003.  
  1004.         self.load()
  1005.  
  1006.         if self.readonly:
  1007.             self._copy()
  1008.  
  1009.         if mask:
  1010.             mask.load()
  1011.             self.im.paste(im, box, mask.im)
  1012.         else:
  1013.             self.im.paste(im, box)
  1014.  
  1015.     ##
  1016.     # Maps this image through a lookup table or function.
  1017.     #
  1018.     # @param lut A lookup table, containing 256 values per band in the
  1019.     #    image. A function can be used instead, it should take a single
  1020.     #    argument. The function is called once for each possible pixel
  1021.     #    value, and the resulting table is applied to all bands of the
  1022.     #    image.
  1023.     # @param mode Output mode (default is same as input).  In the
  1024.     #    current version, this can only be used if the source image
  1025.     #    has mode "L" or "P", and the output has mode "1".
  1026.     # @return An Image object.
  1027.  
  1028.     def point(self, lut, mode=None):
  1029.         "Map image through lookup table"
  1030.  
  1031.         if not isSequenceType(lut):
  1032.             # if it isn't a list, it should be a function
  1033.             if self.mode in ("I", "I;16", "F"):
  1034.                 # check if the function can be used with point_transform
  1035.                 scale, offset = _getscaleoffset(lut)
  1036.                 self.load()
  1037.                 return self._new(self.im.point_transform(scale, offset))
  1038.             # for other modes, convert the function to a table
  1039.             lut = map(lut, range(256)) * self.im.bands
  1040.  
  1041.         if self.mode == "F":
  1042.             # FIXME: _imaging returns a confusing error message for this case
  1043.             raise ValueError("point operation not supported for this mode")
  1044.  
  1045.         self.load()
  1046.         return self._new(self.im.point(lut, mode))
  1047.  
  1048.     ##
  1049.     # Adds or replaces the alpha layer in this image.  If the image
  1050.     # does not have an alpha layer, it's converted to "LA" or "RGBA".
  1051.     # The new layer must be either "L" or "1".
  1052.     #
  1053.     # @param im The new alpha layer.  This can either be an "L" or "1"
  1054.     #    image having the same size as this image, or an integer or
  1055.     #    other color value.
  1056.  
  1057.     def putalpha(self, alpha):
  1058.         "Set alpha layer"
  1059.  
  1060.         self.load()
  1061.  
  1062.         if self.readonly:
  1063.             self._copy()
  1064.  
  1065.         if self.mode not in ("LA", "RGBA"):
  1066.             # attempt to promote self to a matching alpha mode
  1067.             try:
  1068.                 mode = getmodebase(self.mode) + "A"
  1069.                 try:
  1070.                     self.im.setmode(mode)
  1071.                 except (AttributeError, ValueError):
  1072.                     # do things the hard way
  1073.                     im = self.im.convert(mode)
  1074.                     if im.mode not in ("LA", "RGBA"):
  1075.                         raise ValueError # sanity check
  1076.                     self.im = im
  1077.                 self.mode = self.im.mode
  1078.             except (KeyError, ValueError):
  1079.                 raise ValueError("illegal image mode")
  1080.  
  1081.         if self.mode == "LA":
  1082.             band = 1
  1083.         else:
  1084.             band = 3
  1085.  
  1086.         if isImageType(alpha):
  1087.             # alpha layer
  1088.             if alpha.mode not in ("1", "L"):
  1089.                 raise ValueError("illegal image mode")
  1090.             alpha.load()
  1091.             if alpha.mode == "1":
  1092.                 alpha = alpha.convert("L")
  1093.         else:
  1094.             # constant alpha
  1095.             try:
  1096.                 self.im.fillband(band, alpha)
  1097.             except (AttributeError, ValueError):
  1098.                 # do things the hard way
  1099.                 alpha = new("L", self.size, alpha)
  1100.             else:
  1101.                 return
  1102.  
  1103.         self.im.putband(alpha.im, band)
  1104.  
  1105.     ##
  1106.     # Copies pixel data to this image.  This method copies data from a
  1107.     # sequence object into the image, starting at the upper left
  1108.     # corner (0, 0), and continuing until either the image or the
  1109.     # sequence ends.  The scale and offset values are used to adjust
  1110.     # the sequence values: <b>pixel = value*scale + offset</b>.
  1111.     #
  1112.     # @param data A sequence object.
  1113.     # @param scale An optional scale value.  The default is 1.0.
  1114.     # @param offset An optional offset value.  The default is 0.0.
  1115.  
  1116.     def putdata(self, data, scale=1.0, offset=0.0):
  1117.         "Put data from a sequence object into an image."
  1118.  
  1119.         self.load() # hmm...
  1120.         self.im.putdata(data, scale, offset)
  1121.  
  1122.     ##
  1123.     # Attaches a palette to this image.  The image must be a "P" or
  1124.     # "L" image, and the palette sequence must contain 768 integer
  1125.     # values, where each group of three values represent the red,
  1126.     # green, and blue values for the corresponding pixel
  1127.     # index. Instead of an integer sequence, you can use an 8-bit
  1128.     # string.
  1129.     #
  1130.     # @def putpalette(data)
  1131.     # @param data A palette sequence (either a list or a string).
  1132.  
  1133.     def putpalette(self, data, rawmode="RGB"):
  1134.         "Put palette data into an image."
  1135.  
  1136.         self.load()
  1137.         if self.mode not in ("L", "P"):
  1138.             raise ValueError("illegal image mode")
  1139.         if not isStringType(data):
  1140.             data = string.join(map(chr, data), "")
  1141.         self.mode = "P"
  1142.         self.palette = ImagePalette.raw(rawmode, data)
  1143.         self.palette.mode = "RGB"
  1144.         self.load() # install new palette
  1145.  
  1146.     ##
  1147.     # Modifies the pixel at the given position. The colour is given as
  1148.     # a single numerical value for single-band images, and a tuple for
  1149.     # multi-band images.
  1150.     # <p>
  1151.     # Note that this method is relatively slow.  For more extensive
  1152.     # changes, use {@link #Image.paste} or the <b>ImageDraw</b> module
  1153.     # instead.
  1154.     #
  1155.     # @param xy The pixel coordinate, given as (x, y).
  1156.     # @param value The pixel value.
  1157.     # @see #Image.paste
  1158.     # @see #Image.putdata
  1159.     # @see ImageDraw
  1160.  
  1161.     def putpixel(self, xy, value):
  1162.         "Set pixel value"
  1163.  
  1164.         self.load()
  1165.         return self.im.putpixel(xy, value)
  1166.  
  1167.     ##
  1168.     # Returns a resized copy of this image.
  1169.     #
  1170.     # @def resize(size, filter=NEAREST)
  1171.     # @param size The requested size in pixels, as a 2-tuple:
  1172.     #    (width, height).
  1173.     # @param filter An optional resampling filter.  This can be
  1174.     #    one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
  1175.     #    (linear interpolation in a 2x2 environment), <b>BICUBIC</b>
  1176.     #    (cubic spline interpolation in a 4x4 environment), or
  1177.     #    <b>ANTIALIAS</b> (a high-quality downsampling filter).
  1178.     #    If omitted, or if the image has mode "1" or "P", it is
  1179.     #    set <b>NEAREST</b>.
  1180.     # @return An Image object.
  1181.  
  1182.     def resize(self, size, resample=NEAREST):
  1183.         "Resize image"
  1184.  
  1185.         if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
  1186.             raise ValueError("unknown resampling filter")
  1187.  
  1188.         self.load()
  1189.  
  1190.         if self.mode in ("1", "P"):
  1191.             resample = NEAREST
  1192.  
  1193.         if resample == ANTIALIAS:
  1194.             # requires stretch support (imToolkit & PIL 1.1.3)
  1195.             try:
  1196.                 im = self.im.stretch(size, resample)
  1197.             except AttributeError:
  1198.                 raise ValueError("unsupported resampling filter")
  1199.         else:
  1200.             im = self.im.resize(size, resample)
  1201.  
  1202.         return self._new(im)
  1203.  
  1204.     ##
  1205.     # Returns a rotated copy of this image.  This method returns a
  1206.     # copy of this image, rotated the given number of degrees counter
  1207.     # clockwise around its centre.
  1208.     #
  1209.     # @def rotate(angle, filter=NEAREST)
  1210.     # @param angle In degrees counter clockwise.
  1211.     # @param filter An optional resampling filter.  This can be
  1212.     #    one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
  1213.     #    (linear interpolation in a 2x2 environment), or <b>BICUBIC</b>
  1214.     #    (cubic spline interpolation in a 4x4 environment).
  1215.     #    If omitted, or if the image has mode "1" or "P", it is
  1216.     #    set <b>NEAREST</b>.
  1217.     # @return An Image object.
  1218.  
  1219.     def rotate(self, angle, resample=NEAREST):
  1220.         "Rotate image.  Angle given as degrees counter-clockwise."
  1221.  
  1222.         if resample not in (NEAREST, BILINEAR, BICUBIC):
  1223.             raise ValueError("unknown resampling filter")
  1224.  
  1225.         self.load()
  1226.  
  1227.         if self.mode in ("1", "P"):
  1228.             resample = NEAREST
  1229.  
  1230.         return self._new(self.im.rotate(angle, resample))
  1231.  
  1232.     ##
  1233.     # Saves this image under the given filename.  If no format is
  1234.     # specified, the format to use is determined from the filename
  1235.     # extension, if possible.
  1236.     # <p>
  1237.     # Keyword options can be used to provide additional instructions
  1238.     # to the writer. If a writer doesn't recognise an option, it is
  1239.     # silently ignored. The available options are described later in
  1240.     # this handbook.
  1241.     # <p>
  1242.     # You can use a file object instead of a filename. In this case,
  1243.     # you must always specify the format. The file object must
  1244.     # implement the <b>seek</b>, <b>tell</b>, and <b>write</b>
  1245.     # methods, and be opened in binary mode.
  1246.     #
  1247.     # @def save(file, format=None, **options)
  1248.     # @param file File name or file object.
  1249.     # @param format Optional format override.  If omitted, the
  1250.     #    format to use is determined from the filename extension.
  1251.     #    If a file object was used instead of a filename, this
  1252.     #    parameter should always be used.
  1253.     # @param **options Extra parameters to the image writer.
  1254.     # @return None
  1255.     # @exception KeyError If the output format could not be determined
  1256.     #    from the file name.  Use the format option to solve this.
  1257.     # @exception IOError If the file could not be written.  The file
  1258.     #    may have been created, and may contain partial data.
  1259.  
  1260.     def save(self, fp, format=None, **params):
  1261.         "Save image to file or stream"
  1262.  
  1263.         if isStringType(fp):
  1264.             filename = fp
  1265.         else:
  1266.             if hasattr(fp, "name") and isStringType(fp.name):
  1267.                 filename = fp.name
  1268.             else:
  1269.                 filename = ""
  1270.  
  1271.         # may mutate self!
  1272.         self.load()
  1273.  
  1274.         self.encoderinfo = params
  1275.         self.encoderconfig = ()
  1276.  
  1277.         preinit()
  1278.  
  1279.         ext = string.lower(os.path.splitext(filename)[1])
  1280.  
  1281.         if not format:
  1282.             try:
  1283.                 format = EXTENSION[ext]
  1284.             except KeyError:
  1285.                 init()
  1286.                 try:
  1287.                     format = EXTENSION[ext]
  1288.                 except KeyError:
  1289.                     raise KeyError(ext) # unknown extension
  1290.  
  1291.         try:
  1292.             save_handler = SAVE[string.upper(format)]
  1293.         except KeyError:
  1294.             init()
  1295.             save_handler = SAVE[string.upper(format)] # unknown format
  1296.  
  1297.         if isStringType(fp):
  1298.             import __builtin__
  1299.             fp = __builtin__.open(fp, "wb")
  1300.             close = 1
  1301.         else:
  1302.             close = 0
  1303.  
  1304.         try:
  1305.             save_handler(self, fp, filename)
  1306.         finally:
  1307.             # do what we can to clean up
  1308.             if close:
  1309.                 fp.close()
  1310.  
  1311.     ##
  1312.     # Seeks to the given frame in this sequence file. If you seek
  1313.     # beyond the end of the sequence, the method raises an
  1314.     # <b>EOFError</b> exception. When a sequence file is opened, the
  1315.     # library automatically seeks to frame 0.
  1316.     # <p>
  1317.     # Note that in the current version of the library, most sequence
  1318.     # formats only allows you to seek to the next frame.
  1319.     #
  1320.     # @param frame Frame number, starting at 0.
  1321.     # @exception EOFError If the call attempts to seek beyond the end
  1322.     #     of the sequence.
  1323.     # @see #Image.tell
  1324.  
  1325.     def seek(self, frame):
  1326.         "Seek to given frame in sequence file"
  1327.  
  1328.         # overridden by file handlers
  1329.         if frame != 0:
  1330.             raise EOFError
  1331.  
  1332.     ##
  1333.     # Displays this image. This method is mainly intended for
  1334.     # debugging purposes.
  1335.     # <p>
  1336.     # On Unix platforms, this method saves the image to a temporary
  1337.     # PPM file, and calls the <b>xv</b> utility.
  1338.     # <p>
  1339.     # On Windows, it saves the image to a temporary BMP file, and uses
  1340.     # the standard BMP display utility to show it (usually Paint).
  1341.     #
  1342.     # @def show(title=None)
  1343.     # @param title Optional title to use for the image window,
  1344.     #    where possible.
  1345.  
  1346.     def show(self, title=None, command=None):
  1347.         "Display image (for debug purposes only)"
  1348.  
  1349.         _showxv(self, title, command)
  1350.  
  1351.     ##
  1352.     # Split this image into individual bands. This method returns a
  1353.     # tuple of individual image bands from an image. For example,
  1354.     # splitting an "RGB" image creates three new images each
  1355.     # containing a copy of one of the original bands (red, green,
  1356.     # blue).
  1357.     #
  1358.     # @return A tuple containing bands.
  1359.  
  1360.     def split(self):
  1361.         "Split image into bands"
  1362.  
  1363.         ims = []
  1364.         self.load()
  1365.         for i in range(self.im.bands):
  1366.             ims.append(self._new(self.im.getband(i)))
  1367.         return tuple(ims)
  1368.  
  1369.     ##
  1370.     # Returns the current frame number.
  1371.     #
  1372.     # @return Frame number, starting with 0.
  1373.     # @see #Image.seek
  1374.  
  1375.     def tell(self):
  1376.         "Return current frame number"
  1377.  
  1378.         return 0
  1379.  
  1380.     ##
  1381.     # Make this image into a thumbnail.  This method modifies the
  1382.     # image to contain a thumbnail version of itself, no larger than
  1383.     # the given size.  This method calculates an appropriate thumbnail
  1384.     # size to preserve the aspect of the image, calls the {@link
  1385.     # #Image.draft} method to configure the file reader (where
  1386.     # applicable), and finally resizes the image.
  1387.     # <p>
  1388.     # Note that the bilinear and bicubic filters in the current
  1389.     # version of PIL are not well-suited for thumbnail generation.
  1390.     # You should use <b>ANTIALIAS</b> unless speed is much more
  1391.     # important than quality.
  1392.     # <p>
  1393.     # Also note that this function modifies the Image object in place.
  1394.     # If you need to use the full resolution image as well, apply this
  1395.     # method to a {@link #Image.copy} of the original image.
  1396.     #
  1397.     # @param size Requested size.
  1398.     # @param resample Optional resampling filter.  This can be one
  1399.     #    of <b>NEAREST</b>, <b>BILINEAR</b>, <b>BICUBIC</b>, or
  1400.     #    <b>ANTIALIAS</b> (best quality).  If omitted, it defaults
  1401.     #    to <b>NEAREST</b> (this will be changed to ANTIALIAS in a
  1402.     #    future version).
  1403.     # @return None
  1404.  
  1405.     def thumbnail(self, size, resample=NEAREST):
  1406.         "Create thumbnail representation (modifies image in place)"
  1407.  
  1408.         # FIXME: the default resampling filter will be changed
  1409.         # to ANTIALIAS in future versions
  1410.  
  1411.         # preserve aspect ratio
  1412.         x, y = self.size
  1413.         if x > size[0]: y = max(y * size[0] / x, 1); x = size[0]
  1414.         if y > size[1]: x = max(x * size[1] / y, 1); y = size[1]
  1415.         size = x, y
  1416.  
  1417.         if size == self.size:
  1418.             return
  1419.  
  1420.         self.draft(None, size)
  1421.  
  1422.         self.load()
  1423.  
  1424.         try:
  1425.             im = self.resize(size, resample)
  1426.         except ValueError:
  1427.             if resample != ANTIALIAS:
  1428.                 raise
  1429.             im = self.resize(size, NEAREST) # fallback
  1430.  
  1431.         self.im = im.im
  1432.         self.mode = im.mode
  1433.         self.size = size
  1434.  
  1435.         self.readonly = 0
  1436.  
  1437.     # FIXME: the different tranform methods need further explanation
  1438.     # instead of bloating the method docs, add a separate chapter.
  1439.  
  1440.     ##
  1441.     # Transforms this image.  This method creates a new image with the
  1442.     # given size, and the same mode as the original, and copies data
  1443.     # to the new image using the given transform.
  1444.     # <p>
  1445.     # @def transform(size, method, data, resample=NEAREST)
  1446.     # @param size The output size.
  1447.     # @param method The transformation method.  This is one of
  1448.     #   <b>EXTENT</b> (cut out a rectangular subregion), <b>AFFINE</b>
  1449.     #   (affine transform), <b>PERSPECTIVE</b> (perspective
  1450.     #   transform), <b>QUAD</b> (map a quadrilateral to a
  1451.     #   rectangle), or <b>MESH</b> (map a number of source quadrilaterals
  1452.     #   in one operation).
  1453.     # @param data Extra data to the transformation method.
  1454.     # @param resample Optional resampling filter.  It can be one of
  1455.     #    <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
  1456.     #    (linear interpolation in a 2x2 environment), or
  1457.     #    <b>BICUBIC</b> (cubic spline interpolation in a 4x4
  1458.     #    environment). If omitted, or if the image has mode
  1459.     #    "1" or "P", it is set to <b>NEAREST</b>.
  1460.     # @return An Image object.
  1461.  
  1462.     def transform(self, size, method, data=None, resample=NEAREST, fill=1):
  1463.         "Transform image"
  1464.  
  1465.         import ImageTransform
  1466.         if isinstance(method, ImageTransform.Transform):
  1467.             method, data = method.getdata()
  1468.         if data is None:
  1469.             raise ValueError("missing method data")
  1470.         im = new(self.mode, size, None)
  1471.         if method == MESH:
  1472.             # list of quads
  1473.             for box, quad in data:
  1474.                 im.__transformer(box, self, QUAD, quad, resample, fill)
  1475.         else:
  1476.             im.__transformer((0, 0)+size, self, method, data, resample, fill)
  1477.  
  1478.         return im
  1479.  
  1480.     def __transformer(self, box, image, method, data,
  1481.                       resample=NEAREST, fill=1):
  1482.  
  1483.         # FIXME: this should be turned into a lazy operation (?)
  1484.  
  1485.         w = box[2]-box[0]
  1486.         h = box[3]-box[1]
  1487.  
  1488.         if method == AFFINE:
  1489.             # change argument order to match implementation
  1490.             data = (data[2], data[0], data[1],
  1491.                     data[5], data[3], data[4])
  1492.         elif method == EXTENT:
  1493.             # convert extent to an affine transform
  1494.             x0, y0, x1, y1 = data
  1495.             xs = float(x1 - x0) / w
  1496.             ys = float(y1 - y0) / h
  1497.             method = AFFINE
  1498.             data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
  1499.         elif method == PERSPECTIVE:
  1500.             # change argument order to match implementation
  1501.             data = (data[2], data[0], data[1],
  1502.                     data[5], data[3], data[4],
  1503.                     data[6], data[7])
  1504.         elif method == QUAD:
  1505.             # quadrilateral warp.  data specifies the four corners
  1506.             # given as NW, SW, SE, and NE.
  1507.             nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8]
  1508.             x0, y0 = nw; As = 1.0 / w; At = 1.0 / h
  1509.             data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,
  1510.                     (se[0]-sw[0]-ne[0]+x0)*As*At,
  1511.                     y0, (ne[1]-y0)*As, (sw[1]-y0)*At,
  1512.                     (se[1]-sw[1]-ne[1]+y0)*As*At)
  1513.         else:
  1514.             raise ValueError("unknown transformation method")
  1515.  
  1516.         if resample not in (NEAREST, BILINEAR, BICUBIC):
  1517.             raise ValueError("unknown resampling filter")
  1518.  
  1519.         image.load()
  1520.  
  1521.         self.load()
  1522.  
  1523.         if image.mode in ("1", "P"):
  1524.             resample = NEAREST
  1525.  
  1526.         self.im.transform2(box, image.im, method, data, resample, fill)
  1527.  
  1528.     ##
  1529.     # Returns a flipped or rotated copy of this image.
  1530.     #
  1531.     # @param method One of <b>FLIP_LEFT_RIGHT</b>, <b>FLIP_TOP_BOTTOM</b>,
  1532.     # <b>ROTATE_90</b>, <b>ROTATE_180</b>, or <b>ROTATE_270</b>.
  1533.  
  1534.     def transpose(self, method):
  1535.         "Transpose image (flip or rotate in 90 degree steps)"
  1536.  
  1537.         self.load()
  1538.         im = self.im.transpose(method)
  1539.         return self._new(im)
  1540.  
  1541. # --------------------------------------------------------------------
  1542. # Lazy operations
  1543.  
  1544. class _ImageCrop(Image):
  1545.  
  1546.     def __init__(self, im, box):
  1547.  
  1548.         Image.__init__(self)
  1549.  
  1550.         x0, y0, x1, y1 = box
  1551.         if x1 < x0:
  1552.             x1 = x0
  1553.         if y1 < y0:
  1554.             y1 = y0
  1555.  
  1556.         self.mode = im.mode
  1557.         self.size = x1-x0, y1-y0
  1558.  
  1559.         self.__crop = x0, y0, x1, y1
  1560.  
  1561.         self.im = im.im
  1562.  
  1563.     def load(self):
  1564.  
  1565.         # lazy evaluation!
  1566.         if self.__crop:
  1567.             self.im = self.im.crop(self.__crop)
  1568.             self.__crop = None
  1569.  
  1570.         # FIXME: future versions should optimize crop/paste
  1571.         # sequences!
  1572.  
  1573. # --------------------------------------------------------------------
  1574. # Factories
  1575.  
  1576. #
  1577. # Debugging
  1578.  
  1579. def _wedge():
  1580.     "Create greyscale wedge (for debugging only)"
  1581.  
  1582.     return Image()._new(core.wedge("L"))
  1583.  
  1584. ##
  1585. # Creates a new image with the given mode and size.
  1586. #
  1587. # @param mode The mode to use for the new image.
  1588. # @param size A 2-tuple, containing (width, height) in pixels.
  1589. # @param color What colour to use for the image.  Default is black.
  1590. #    If given, this should be a single integer or floating point value
  1591. #    for single-band modes, and a tuple for multi-band modes (one value
  1592. #    per band).  When creating RGB images, you can also use colour
  1593. #    strings as supported by the ImageColor module.  If the colour is
  1594. #    None, the image is not initialised.
  1595. # @return An Image object.
  1596.  
  1597. def new(mode, size, color=0):
  1598.     "Create a new image"
  1599.  
  1600.     if color is None:
  1601.         # don't initialize
  1602.         return Image()._new(core.new(mode, size))
  1603.  
  1604.     if isStringType(color):
  1605.         # css3-style specifier
  1606.  
  1607.         import ImageColor
  1608.         color = ImageColor.getcolor(color, mode)
  1609.  
  1610.     return Image()._new(core.fill(mode, size, color))
  1611.  
  1612. ##
  1613. # Creates an image memory from pixel data in a string.
  1614. # <p>
  1615. # In its simplest form, this function takes three arguments
  1616. # (mode, size, and unpacked pixel data).
  1617. # <p>
  1618. # You can also use any pixel decoder supported by PIL.  For more
  1619. # information on available decoders, see the section <a
  1620. # href="pil-decoder.htm"><i>Writing Your Own File Decoder</i></a>.
  1621. # <p>
  1622. # Note that this function decodes pixel data only, not entire images.
  1623. # If you have an entire image in a string, wrap it in a
  1624. # <b>StringIO</b> object, and use {@link #open} to load it.
  1625. #
  1626. # @param mode The image mode.
  1627. # @param size The image size.
  1628. # @param data An 8-bit string containing raw data for the given mode.
  1629. # @param decoder_name What decoder to use.
  1630. # @param *args Additional parameters for the given decoder.
  1631. # @return An Image object.
  1632.  
  1633. def fromstring(mode, size, data, decoder_name="raw", *args):
  1634.     "Load image from string"
  1635.  
  1636.     # may pass tuple instead of argument list
  1637.     if len(args) == 1 and isTupleType(args[0]):
  1638.         args = args[0]
  1639.  
  1640.     if decoder_name == "raw" and args == ():
  1641.         args = mode
  1642.  
  1643.     im = new(mode, size)
  1644.     im.fromstring(data, decoder_name, args)
  1645.     return im
  1646.  
  1647. ##
  1648. # (New in 1.1.4) Creates an image memory from pixel data in a string
  1649. # or byte buffer.
  1650. # <p>
  1651. # This function is similar to {@link #fromstring}, but uses data in
  1652. # the byte buffer, where possible.  This means that changes to the
  1653. # original buffer object are reflected in this image).  Not all modes
  1654. # can share memory; support modes include "L", "RGBX", "RGBA", and
  1655. # "CMYK".  For other modes, this function behaves like a corresponding
  1656. # call to the <b>fromstring</b> function.
  1657. # <p>
  1658. # Note that this function decodes pixel data only, not entire images.
  1659. # If you have an entire image file in a string, wrap it in a
  1660. # <b>StringIO</b> object, and use {@link #open} to load it.
  1661. #
  1662. # @param mode The image mode.
  1663. # @param size The image size.
  1664. # @param data An 8-bit string or other buffer object containing raw
  1665. #     data for the given mode.
  1666. # @param decoder_name What decoder to use.
  1667. # @param *args Additional parameters for the given decoder.
  1668. # @return An Image object.
  1669. # @since 1.1.4
  1670.  
  1671. def frombuffer(mode, size, data, decoder_name="raw", *args):
  1672.     "Load image from string or buffer"
  1673.  
  1674.     # may pass tuple instead of argument list
  1675.     if len(args) == 1 and isTupleType(args[0]):
  1676.         args = args[0]
  1677.  
  1678.     if decoder_name == "raw":
  1679.         if args == ():
  1680.             args = mode, 0, -1
  1681.         if args[0] in _MAPMODES:
  1682.             im = new(mode, (1,1))
  1683.             im = im._new(
  1684.                 core.map_buffer(data, size, decoder_name, None, 0, args)
  1685.                 )
  1686.             im.readonly = 1
  1687.             return im
  1688.  
  1689.     return apply(fromstring, (mode, size, data, decoder_name, args))
  1690.  
  1691. ##
  1692. # Opens and identifies the given image file.
  1693. # <p>
  1694. # This is a lazy operation; this function identifies the file, but the
  1695. # actual image data is not read from the file until you try to process
  1696. # the data (or call the {@link #Image.load} method).
  1697. #
  1698. # @def open(file, mode="r")
  1699. # @param file A filename (string) or a file object.  The file object
  1700. #    must implement <b>read</b>, <b>seek</b>, and <b>tell</b> methods,
  1701. #    and be opened in binary mode.
  1702. # @param mode The mode.  If given, this argument must be "r".
  1703. # @return An Image object.
  1704. # @exception IOError If the file cannot be found, or the image cannot be
  1705. #    opened and identified.
  1706. # @see #new
  1707.  
  1708. def open(fp, mode="r"):
  1709.     "Open an image file, without loading the raster data"
  1710.  
  1711.     if mode != "r":
  1712.         raise ValueError("bad mode")
  1713.  
  1714.     if isStringType(fp):
  1715.         import __builtin__
  1716.         filename = fp
  1717.         fp = __builtin__.open(fp, "rb")
  1718.     else:
  1719.         filename = ""
  1720.  
  1721.     prefix = fp.read(16)
  1722.  
  1723.     preinit()
  1724.  
  1725.     for i in ID:
  1726.         try:
  1727.             factory, accept = OPEN[i]
  1728.             if not accept or accept(prefix):
  1729.                 fp.seek(0)
  1730.                 return factory(fp, filename)
  1731.         except (SyntaxError, IndexError, TypeError):
  1732.             pass
  1733.  
  1734.     init()
  1735.  
  1736.     for i in ID:
  1737.         try:
  1738.             factory, accept = OPEN[i]
  1739.             if not accept or accept(prefix):
  1740.                 fp.seek(0)
  1741.                 return factory(fp, filename)
  1742.         except (SyntaxError, IndexError, TypeError):
  1743.             pass
  1744.  
  1745.     raise IOError("cannot identify image file")
  1746.  
  1747. #
  1748. # Image processing.
  1749.  
  1750. ##
  1751. # Creates a new image by interpolating between two input images, using
  1752. # a constant alpha.
  1753. #
  1754. # <pre>
  1755. #    out = image1 * (1.0 - alpha) + image2 * alpha
  1756. # </pre>
  1757. #
  1758. # @param im1 The first image.
  1759. # @param im2 The second image.  Must have the same mode and size as
  1760. #    the first image.
  1761. # @param alpha The interpolation alpha factor.  If alpha is 0.0, a
  1762. #    copy of the first image is returned. If alpha is 1.0, a copy of
  1763. #    the second image is returned. There are no restrictions on the
  1764. #    alpha value. If necessary, the result is clipped to fit into
  1765. #    the allowed output range.
  1766. # @return An Image object.
  1767.  
  1768. def blend(im1, im2, alpha):
  1769.     "Interpolate between images."
  1770.  
  1771.     im1.load()
  1772.     im2.load()
  1773.     return im1._new(core.blend(im1.im, im2.im, alpha))
  1774.  
  1775. ##
  1776. # Creates a new image by interpolating between two input images,
  1777. # using the mask as alpha.
  1778. #
  1779. # @param image1 The first image.
  1780. # @param image2 The second image.  Must have the same mode and
  1781. #    size as the first image.
  1782. # @param mask A mask image.  This image can can have mode
  1783. #    "1", "L", or "RGBA", and must have the same size as the
  1784. #    other two images.
  1785.  
  1786. def composite(image1, image2, mask):
  1787.     "Create composite image by blending images using a transparency mask"
  1788.  
  1789.     image = image2.copy()
  1790.     image.paste(image1, None, mask)
  1791.     return image
  1792.  
  1793. ##
  1794. # Applies the function (which should take one argument) to each pixel
  1795. # in the given image. If the image has more than one band, the same
  1796. # function is applied to each band. Note that the function is
  1797. # evaluated once for each possible pixel value, so you cannot use
  1798. # random components or other generators.
  1799. #
  1800. # @def eval(image, function)
  1801. # @param image The input image.
  1802. # @param function A function object, taking one integer argument.
  1803. # @return An Image object.
  1804.  
  1805. def eval(image, *args):
  1806.     "Evaluate image expression"
  1807.  
  1808.     return image.point(args[0])
  1809.  
  1810. ##
  1811. # Creates a new image from a number of single-band images.
  1812. #
  1813. # @param mode The mode to use for the output image.
  1814. # @param bands A sequence containing one single-band image for
  1815. #     each band in the output image.  All bands must have the
  1816. #     same size.
  1817. # @return An Image object.
  1818.  
  1819. def merge(mode, bands):
  1820.     "Merge a set of single band images into a new multiband image."
  1821.  
  1822.     if getmodebands(mode) != len(bands) or "*" in mode:
  1823.         raise ValueError("wrong number of bands")
  1824.     for im in bands[1:]:
  1825.         if im.mode != getmodetype(mode):
  1826.             raise ValueError("mode mismatch")
  1827.         if im.size != bands[0].size:
  1828.             raise ValueError("size mismatch")
  1829.     im = core.new(mode, bands[0].size)
  1830.     for i in range(getmodebands(mode)):
  1831.         bands[i].load()
  1832.         im.putband(bands[i].im, i)
  1833.     return bands[0]._new(im)
  1834.  
  1835. # --------------------------------------------------------------------
  1836. # Plugin registry
  1837.  
  1838. ##
  1839. # Register an image file plugin.  This function should not be used
  1840. # in application code.
  1841. #
  1842. # @param id An image format identifier.
  1843. # @param factory An image file factory method.
  1844. # @param accept An optional function that can be used to quickly
  1845. #    reject images having another format.
  1846.  
  1847. def register_open(id, factory, accept=None):
  1848.     id = string.upper(id)
  1849.     ID.append(id)
  1850.     OPEN[id] = factory, accept
  1851.  
  1852. ##
  1853. # Registers an image MIME type.  This function should not be used
  1854. # in application code.
  1855. #
  1856. # @param id An image format identifier.
  1857. # @param mimetype The image MIME type for this format.
  1858.  
  1859. def register_mime(id, mimetype):
  1860.     MIME[string.upper(id)] = mimetype
  1861.  
  1862. ##
  1863. # Registers an image save function.  This function should not be
  1864. # used in application code.
  1865. #
  1866. # @param id An image format identifier.
  1867. # @param driver A function to save images in this format.
  1868.  
  1869. def register_save(id, driver):
  1870.     SAVE[string.upper(id)] = driver
  1871.  
  1872. ##
  1873. # Registers an image extension.  This function should not be
  1874. # used in application code.
  1875. #
  1876. # @param id An image format identifier.
  1877. # @param extension An extension used for this format.
  1878.  
  1879. def register_extension(id, extension):
  1880.     EXTENSION[string.lower(extension)] = string.upper(id)
  1881.  
  1882.  
  1883. # --------------------------------------------------------------------
  1884. # Simple display support
  1885.  
  1886. def _showxv(image, title=None, command=None):
  1887.  
  1888.     if os.name == "nt":
  1889.         format = "BMP"
  1890.         if not command:
  1891.             command = "start"
  1892.     elif sys.platform == "darwin":
  1893.         format = "JPEG"
  1894.         if not command:
  1895.             command = "open -a /Applications/Preview.app"
  1896.     else:
  1897.         format = None
  1898.         if not command:
  1899.             command = "xv"
  1900.             if title:
  1901.                 command = command + " -name \"%s\"" % title
  1902.  
  1903.     if image.mode == "I;16":
  1904.         # @PIL88 @PIL101
  1905.         # "I;16" isn't an 'official' mode, but we still want to
  1906.         # provide a simple way to show 16-bit images.
  1907.         base = "L"
  1908.     else:
  1909.         base = getmodebase(image.mode)
  1910.     if base != image.mode and image.mode != "1":
  1911.         file = image.convert(base)._dump(format=format)
  1912.     else:
  1913.         file = image._dump(format=format)
  1914.  
  1915.     if os.name == "nt":
  1916.         os.system("%s %s" % (command, file))
  1917.         # FIXME: this leaves temporary files around...
  1918.     elif sys.platform == "darwin":
  1919.         # on darwin open returns immediately resulting in the temp
  1920.         # file removal while app is opening
  1921.         os.system("(%s %s; sleep 20; rm -f %s)&" % (command, file, file))
  1922.     else:
  1923.         os.system("(%s %s; rm -f %s)&" % (command, file, file))
  1924.