home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / PIL / Image.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  37.3 KB  |  1,374 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. VERSION = '1.1.6'
  5.  
  6. try:
  7.     import warnings
  8. except ImportError:
  9.     warnings = None
  10.  
  11.  
  12. class _imaging_not_installed:
  13.     
  14.     def __getattr__(self, id):
  15.         raise ImportError('The _imaging C module is not installed')
  16.  
  17.  
  18.  
  19. try:
  20.     __import__('FixTk')
  21. except ImportError:
  22.     pass
  23.  
  24.  
  25. try:
  26.     import _imaging
  27.     core = _imaging
  28.     del _imaging
  29. except ImportError:
  30.     v = None
  31.     core = _imaging_not_installed()
  32.     if str(v)[:20] == 'Module use of python' and warnings:
  33.         warnings.warn('The _imaging extension was built for another version of Python; most PIL functions will be disabled', RuntimeWarning)
  34.     
  35. except:
  36.     warnings
  37.  
  38. import ImageMode
  39. import ImagePalette
  40. import os
  41. import stat
  42. import string
  43. import sys
  44. from types import IntType, StringType, TupleType
  45.  
  46. try:
  47.     UnicodeStringType = type(unicode(''))
  48.     
  49.     def isStringType(t):
  50.         if not isinstance(t, StringType):
  51.             pass
  52.         return isinstance(t, UnicodeStringType)
  53.  
  54. except NameError:
  55.     
  56.     def isStringType(t):
  57.         return isinstance(t, StringType)
  58.  
  59.  
  60.  
  61. def isTupleType(t):
  62.     return isinstance(t, TupleType)
  63.  
  64.  
  65. def isImageType(t):
  66.     return hasattr(t, 'im')
  67.  
  68.  
  69. def isDirectory(f):
  70.     if isStringType(f):
  71.         pass
  72.     return os.path.isdir(f)
  73.  
  74. from operator import isNumberType, isSequenceType
  75. DEBUG = 0
  76. NONE = 0
  77. FLIP_LEFT_RIGHT = 0
  78. FLIP_TOP_BOTTOM = 1
  79. ROTATE_90 = 2
  80. ROTATE_180 = 3
  81. ROTATE_270 = 4
  82. AFFINE = 0
  83. EXTENT = 1
  84. PERSPECTIVE = 2
  85. QUAD = 3
  86. MESH = 4
  87. NONE = 0
  88. NEAREST = 0
  89. ANTIALIAS = 1
  90. LINEAR = BILINEAR = 2
  91. CUBIC = BICUBIC = 3
  92. NONE = 0
  93. NEAREST = 0
  94. ORDERED = 1
  95. RASTERIZE = 2
  96. FLOYDSTEINBERG = 3
  97. WEB = 0
  98. ADAPTIVE = 1
  99. NORMAL = 0
  100. SEQUENCE = 1
  101. CONTAINER = 2
  102. ID = []
  103. OPEN = { }
  104. MIME = { }
  105. SAVE = { }
  106. EXTENSION = { }
  107. _MODEINFO = {
  108.     '1': ('L', 'L', ('1',)),
  109.     'L': ('L', 'L', ('L',)),
  110.     'I': ('L', 'I', ('I',)),
  111.     'F': ('L', 'F', ('F',)),
  112.     'P': ('RGB', 'L', ('P',)),
  113.     'RGB': ('RGB', 'L', ('R', 'G', 'B')),
  114.     'RGBX': ('RGB', 'L', ('R', 'G', 'B', 'X')),
  115.     'RGBA': ('RGB', 'L', ('R', 'G', 'B', 'A')),
  116.     'CMYK': ('RGB', 'L', ('C', 'M', 'Y', 'K')),
  117.     'YCbCr': ('RGB', 'L', ('Y', 'Cb', 'Cr')) }
  118. if sys.byteorder == 'little':
  119.     _ENDIAN = '<'
  120. else:
  121.     _ENDIAN = '>'
  122. _MODE_CONV = {
  123.     '1': ('|b1', None),
  124.     'L': ('|u1', None),
  125.     'I': ('%si4' % _ENDIAN, None),
  126.     'I;16': ('%si2' % _ENDIAN, None),
  127.     'F': ('%sf4' % _ENDIAN, None),
  128.     'P': ('|u1', None),
  129.     'RGB': ('|u1', 3),
  130.     'RGBX': ('|u1', 4),
  131.     'RGBA': ('|u1', 4),
  132.     'CMYK': ('|u1', 4),
  133.     'YCbCr': ('|u1', 4) }
  134.  
  135. def _conv_type_shape(im):
  136.     shape = im.size[::-1]
  137.     (typ, extra) = _MODE_CONV[im.mode]
  138.     if extra is None:
  139.         return (shape, typ)
  140.     return (shape + (extra,), typ)
  141.  
  142. MODES = _MODEINFO.keys()
  143. MODES.sort()
  144. _MAPMODES = ('L', 'P', 'RGBX', 'RGBA', 'CMYK', 'I;16', 'I;16B')
  145.  
  146. def getmodebase(mode):
  147.     return ImageMode.getmode(mode).basemode
  148.  
  149.  
  150. def getmodetype(mode):
  151.     return ImageMode.getmode(mode).basetype
  152.  
  153.  
  154. def getmodebandnames(mode):
  155.     return ImageMode.getmode(mode).bands
  156.  
  157.  
  158. def getmodebands(mode):
  159.     return len(ImageMode.getmode(mode).bands)
  160.  
  161. _initialized = 0
  162.  
  163. def preinit():
  164.     '''Load standard file format drivers.'''
  165.     global _initialized
  166.     if _initialized >= 1:
  167.         return None
  168.     
  169.     try:
  170.         import BmpImagePlugin
  171.     except ImportError:
  172.         _initialized >= 1
  173.         _initialized >= 1
  174.     except:
  175.         _initialized >= 1
  176.  
  177.     
  178.     try:
  179.         import GifImagePlugin
  180.     except ImportError:
  181.         _initialized >= 1
  182.         _initialized >= 1
  183.     except:
  184.         _initialized >= 1
  185.  
  186.     
  187.     try:
  188.         import JpegImagePlugin
  189.     except ImportError:
  190.         _initialized >= 1
  191.         _initialized >= 1
  192.     except:
  193.         _initialized >= 1
  194.  
  195.     
  196.     try:
  197.         import PpmImagePlugin
  198.     except ImportError:
  199.         _initialized >= 1
  200.         _initialized >= 1
  201.     except:
  202.         _initialized >= 1
  203.  
  204.     
  205.     try:
  206.         import PngImagePlugin
  207.     except ImportError:
  208.         _initialized >= 1
  209.         _initialized >= 1
  210.     except:
  211.         _initialized >= 1
  212.  
  213.     _initialized = 1
  214.  
  215.  
  216. def init():
  217.     '''Load all file format drivers.'''
  218.     global _initialized
  219.     if _initialized >= 2:
  220.         return None
  221.     visited = { }
  222.     directories = sys.path
  223.     
  224.     try:
  225.         directories = directories + [
  226.             os.path.dirname(__file__)]
  227.     except NameError:
  228.         _initialized >= 2
  229.         _initialized >= 2
  230.     except:
  231.         _initialized >= 2
  232.  
  233.     for directory in filter(isDirectory, directories):
  234.         fullpath = os.path.abspath(directory)
  235.         if visited.has_key(fullpath):
  236.             continue
  237.         
  238.         for file in os.listdir(directory):
  239.             if file[-14:] == 'ImagePlugin.py':
  240.                 (f, e) = os.path.splitext(file)
  241.                 
  242.                 try:
  243.                     sys.path.insert(0, directory)
  244.                     
  245.                     try:
  246.                         __import__(f, globals(), locals(), [])
  247.                     finally:
  248.                         del sys.path[0]
  249.  
  250.                 except ImportError:
  251.                     if DEBUG:
  252.                         print 'Image: failed to import', f, ':', sys.exc_value
  253.                     
  254.                 except:
  255.                     DEBUG
  256.                 
  257.  
  258.             None<EXCEPTION MATCH>ImportError
  259.         
  260.         visited[fullpath] = None
  261.     
  262.     if OPEN or SAVE:
  263.         _initialized = 2
  264.     
  265.  
  266.  
  267. def _getdecoder(mode, decoder_name, args, extra = ()):
  268.     if args is None:
  269.         args = ()
  270.     elif not isTupleType(args):
  271.         args = (args,)
  272.     
  273.     
  274.     try:
  275.         decoder = getattr(core, decoder_name + '_decoder')
  276.         return apply(decoder, (mode,) + args + extra)
  277.     except AttributeError:
  278.         raise IOError('decoder %s not available' % decoder_name)
  279.  
  280.  
  281.  
  282. def _getencoder(mode, encoder_name, args, extra = ()):
  283.     if args is None:
  284.         args = ()
  285.     elif not isTupleType(args):
  286.         args = (args,)
  287.     
  288.     
  289.     try:
  290.         encoder = getattr(core, encoder_name + '_encoder')
  291.         return apply(encoder, (mode,) + args + extra)
  292.     except AttributeError:
  293.         raise IOError('encoder %s not available' % encoder_name)
  294.  
  295.  
  296.  
  297. class _E:
  298.     
  299.     def __init__(self, data):
  300.         self.data = data
  301.  
  302.     
  303.     def __coerce__(self, other):
  304.         return (self, _E(other))
  305.  
  306.     
  307.     def __add__(self, other):
  308.         return _E((self.data, '__add__', other.data))
  309.  
  310.     
  311.     def __mul__(self, other):
  312.         return _E((self.data, '__mul__', other.data))
  313.  
  314.  
  315.  
  316. def _getscaleoffset(expr):
  317.     stub = [
  318.         'stub']
  319.     data = expr(_E(stub)).data
  320.     
  321.     try:
  322.         (a, b, c) = data
  323.         if a is stub and b == '__mul__' and isNumberType(c):
  324.             return (c, 0)
  325.         if a is stub and b == '__add__' and isNumberType(c):
  326.             return (1, c)
  327.     except TypeError:
  328.         pass
  329.  
  330.     
  331.     try:
  332.         (a, b, c) = ()
  333.         d = data
  334.         e = None
  335.         if a is stub and b == '__mul__' and isNumberType(c) and d == '__add__' and isNumberType(e):
  336.             return (c, e)
  337.     except TypeError:
  338.         pass
  339.  
  340.     raise ValueError('illegal expression')
  341.  
  342.  
  343. class Image:
  344.     format = None
  345.     format_description = None
  346.     
  347.     def __init__(self):
  348.         self.im = None
  349.         self.mode = ''
  350.         self.size = (0, 0)
  351.         self.palette = None
  352.         self.info = { }
  353.         self.category = NORMAL
  354.         self.readonly = 0
  355.  
  356.     
  357.     def _new(self, im):
  358.         new = Image()
  359.         new.im = im
  360.         new.mode = im.mode
  361.         new.size = im.size
  362.         new.palette = self.palette
  363.         if im.mode == 'P':
  364.             new.palette = ImagePalette.ImagePalette()
  365.         
  366.         
  367.         try:
  368.             new.info = self.info.copy()
  369.         except AttributeError:
  370.             new.info = { }
  371.             for k, v in self.info:
  372.                 new.info[k] = v
  373.             
  374.  
  375.         return new
  376.  
  377.     _makeself = _new
  378.     
  379.     def _copy(self):
  380.         self.load()
  381.         self.im = self.im.copy()
  382.         self.readonly = 0
  383.  
  384.     
  385.     def _dump(self, file = None, format = None):
  386.         import tempfile
  387.         if not file:
  388.             file = tempfile.mktemp()
  389.         
  390.         self.load()
  391.         if not format or format == 'PPM':
  392.             self.im.save_ppm(file)
  393.         else:
  394.             file = file + '.' + format
  395.             self.save(file, format)
  396.         return file
  397.  
  398.     
  399.     def __getattr__(self, name):
  400.         if name == '__array_interface__':
  401.             new = { }
  402.             (shape, typestr) = _conv_type_shape(self)
  403.             new['shape'] = shape
  404.             new['typestr'] = typestr
  405.             new['data'] = self.tostring()
  406.             return new
  407.         raise AttributeError(name)
  408.  
  409.     
  410.     def tostring(self, encoder_name = 'raw', *args):
  411.         '''Return image as a binary string'''
  412.         if len(args) == 1 and isTupleType(args[0]):
  413.             args = args[0]
  414.         
  415.         if encoder_name == 'raw' and args == ():
  416.             args = self.mode
  417.         
  418.         self.load()
  419.         e = _getencoder(self.mode, encoder_name, args)
  420.         e.setimage(self.im)
  421.         bufsize = max(65536, self.size[0] * 4)
  422.         data = []
  423.         while None:
  424.             (l, s, d) = e.encode(bufsize)
  425.             if s:
  426.                 break
  427.                 continue
  428.             continue
  429.             if s < 0:
  430.                 raise RuntimeError('encoder error %d in tostring' % s)
  431.             s < 0
  432.             return string.join(data, '')
  433.  
  434.     
  435.     def tobitmap(self, name = 'image'):
  436.         '''Return image as an XBM bitmap'''
  437.         self.load()
  438.         if self.mode != '1':
  439.             raise ValueError('not a bitmap')
  440.         self.mode != '1'
  441.         data = self.tostring('xbm')
  442.         return string.join([
  443.             '#define %s_width %d\n' % (name, self.size[0]),
  444.             '#define %s_height %d\n' % (name, self.size[1]),
  445.             'static char %s_bits[] = {\n' % name,
  446.             data,
  447.             '};'], '')
  448.  
  449.     
  450.     def fromstring(self, data, decoder_name = 'raw', *args):
  451.         '''Load data to image from binary string'''
  452.         if len(args) == 1 and isTupleType(args[0]):
  453.             args = args[0]
  454.         
  455.         if decoder_name == 'raw' and args == ():
  456.             args = self.mode
  457.         
  458.         d = _getdecoder(self.mode, decoder_name, args)
  459.         d.setimage(self.im)
  460.         s = d.decode(data)
  461.         if s[0] >= 0:
  462.             raise ValueError('not enough image data')
  463.         s[0] >= 0
  464.         if s[1] != 0:
  465.             raise ValueError('cannot decode image data')
  466.         s[1] != 0
  467.  
  468.     
  469.     def load(self):
  470.         '''Explicitly load pixel data.'''
  471.         if self.im and self.palette and self.palette.dirty:
  472.             apply(self.im.putpalette, self.palette.getdata())
  473.             self.palette.dirty = 0
  474.             self.palette.mode = 'RGB'
  475.             self.palette.rawmode = None
  476.             if self.info.has_key('transparency'):
  477.                 self.im.putpalettealpha(self.info['transparency'], 0)
  478.                 self.palette.mode = 'RGBA'
  479.             
  480.         
  481.         if self.im:
  482.             return self.im.pixel_access(self.readonly)
  483.  
  484.     
  485.     def verify(self):
  486.         '''Verify file contents.'''
  487.         pass
  488.  
  489.     
  490.     def convert(self, mode = None, data = None, dither = None, palette = WEB, colors = 256):
  491.         '''Convert to other pixel format'''
  492.         if not mode:
  493.             if self.mode == 'P':
  494.                 self.load()
  495.                 if self.palette:
  496.                     mode = self.palette.mode
  497.                 else:
  498.                     mode = 'RGB'
  499.             else:
  500.                 return self.copy()
  501.         self.mode == 'P'
  502.         self.load()
  503.         if data:
  504.             if mode not in ('L', 'RGB'):
  505.                 raise ValueError('illegal conversion')
  506.             mode not in ('L', 'RGB')
  507.             im = self.im.convert_matrix(mode, data)
  508.             return self._new(im)
  509.         if mode == 'P' and palette == ADAPTIVE:
  510.             im = self.im.quantize(colors)
  511.             return self._new(im)
  512.         
  513.         try:
  514.             im = self.im.convert(mode, dither)
  515.         except ValueError:
  516.             None if dither is None else data
  517.             None if dither is None else data
  518.             
  519.             try:
  520.                 im = self.im.convert(getmodebase(self.mode))
  521.                 im = im.convert(mode, dither)
  522.             except KeyError:
  523.                 raise ValueError('illegal conversion')
  524.             except:
  525.                 None<EXCEPTION MATCH>KeyError
  526.             
  527.  
  528.             None<EXCEPTION MATCH>KeyError
  529.  
  530.         return self._new(im)
  531.  
  532.     
  533.     def quantize(self, colors = 256, method = 0, kmeans = 0, palette = None):
  534.         self.load()
  535.         if palette:
  536.             palette.load()
  537.             if palette.mode != 'P':
  538.                 raise ValueError('bad mode for palette image')
  539.             palette.mode != 'P'
  540.             if self.mode != 'RGB' and self.mode != 'L':
  541.                 raise ValueError('only RGB or L mode images can be quantized to a palette')
  542.             self.mode != 'L'
  543.             im = self.im.convert('P', 1, palette.im)
  544.             return self._makeself(im)
  545.         im = self.im.quantize(colors, method, kmeans)
  546.         return self._new(im)
  547.  
  548.     
  549.     def copy(self):
  550.         '''Copy raster data'''
  551.         self.load()
  552.         im = self.im.copy()
  553.         return self._new(im)
  554.  
  555.     
  556.     def crop(self, box = None):
  557.         '''Crop region from image'''
  558.         self.load()
  559.         if box is None:
  560.             return self.copy()
  561.         return _ImageCrop(self, box)
  562.  
  563.     
  564.     def draft(self, mode, size):
  565.         '''Configure image decoder'''
  566.         pass
  567.  
  568.     
  569.     def _expand(self, xmargin, ymargin = None):
  570.         if ymargin is None:
  571.             ymargin = xmargin
  572.         
  573.         self.load()
  574.         return self._new(self.im.expand(xmargin, ymargin, 0))
  575.  
  576.     
  577.     def filter(self, filter):
  578.         '''Apply environment filter to image'''
  579.         self.load()
  580.         Filter = Filter
  581.         import ImageFilter
  582.         if not isinstance(filter, Filter):
  583.             filter = filter()
  584.         
  585.         if self.im.bands == 1:
  586.             return self._new(filter.filter(self.im))
  587.         ims = []
  588.         for c in range(self.im.bands):
  589.             ims.append(self._new(filter.filter(self.im.getband(c))))
  590.         
  591.         return merge(self.mode, ims)
  592.  
  593.     
  594.     def getbands(self):
  595.         '''Get band names'''
  596.         return ImageMode.getmode(self.mode).bands
  597.  
  598.     
  599.     def getbbox(self):
  600.         '''Get bounding box of actual data (non-zero pixels) in image'''
  601.         self.load()
  602.         return self.im.getbbox()
  603.  
  604.     
  605.     def getcolors(self, maxcolors = 256):
  606.         '''Get colors from image, up to given limit'''
  607.         self.load()
  608.         if self.mode in ('1', 'L', 'P'):
  609.             h = self.im.histogram()
  610.             out = []
  611.             for i in range(256):
  612.                 if h[i]:
  613.                     out.append((h[i], i))
  614.                     continue
  615.             
  616.             if len(out) > maxcolors:
  617.                 return None
  618.             return out
  619.         return self.im.getcolors(maxcolors)
  620.  
  621.     
  622.     def getdata(self, band = None):
  623.         '''Get image data as sequence object.'''
  624.         self.load()
  625.         if band is not None:
  626.             return self.im.getband(band)
  627.         return self.im
  628.  
  629.     
  630.     def getextrema(self):
  631.         '''Get min/max value'''
  632.         self.load()
  633.         if self.im.bands > 1:
  634.             extrema = []
  635.             for i in range(self.im.bands):
  636.                 extrema.append(self.im.getband(i).getextrema())
  637.             
  638.             return tuple(extrema)
  639.         return self.im.getextrema()
  640.  
  641.     
  642.     def getim(self):
  643.         '''Get PyCObject pointer to internal image memory'''
  644.         self.load()
  645.         return self.im.ptr
  646.  
  647.     
  648.     def getpalette(self):
  649.         '''Get palette contents.'''
  650.         self.load()
  651.         
  652.         try:
  653.             return map(ord, self.im.getpalette())
  654.         except ValueError:
  655.             return None
  656.  
  657.  
  658.     
  659.     def getpixel(self, xy):
  660.         '''Get pixel value'''
  661.         self.load()
  662.         return self.im.getpixel(xy)
  663.  
  664.     
  665.     def getprojection(self):
  666.         '''Get projection to x and y axes'''
  667.         self.load()
  668.         (x, y) = self.im.getprojection()
  669.         return (map(ord, x), map(ord, y))
  670.  
  671.     
  672.     def histogram(self, mask = None, extrema = None):
  673.         '''Take histogram of image'''
  674.         self.load()
  675.         if mask:
  676.             mask.load()
  677.             return self.im.histogram((0, 0), mask.im)
  678.         if self.mode in ('I', 'F'):
  679.             if extrema is None:
  680.                 extrema = self.getextrema()
  681.             
  682.             return self.im.histogram(extrema)
  683.         return self.im.histogram()
  684.  
  685.     
  686.     def offset(self, xoffset, yoffset = None):
  687.         '''(deprecated) Offset image in horizontal and/or vertical direction'''
  688.         if warnings:
  689.             warnings.warn("'offset' is deprecated; use 'ImageChops.offset' instead", DeprecationWarning, stacklevel = 2)
  690.         
  691.         import ImageChops
  692.         return ImageChops.offset(self, xoffset, yoffset)
  693.  
  694.     
  695.     def paste(self, im, box = None, mask = None):
  696.         '''Paste other image into region'''
  697.         if isImageType(box) and mask is None:
  698.             mask = box
  699.             box = None
  700.         
  701.         if box is None:
  702.             box = (0, 0) + self.size
  703.         
  704.         if len(box) == 2:
  705.             if isImageType(im):
  706.                 size = im.size
  707.             elif isImageType(mask):
  708.                 size = mask.size
  709.             else:
  710.                 raise ValueError('cannot determine region size; use 4-item box')
  711.             box = isImageType(im) + (box[0] + size[0], box[1] + size[1])
  712.         
  713.         if isStringType(im):
  714.             import ImageColor
  715.             im = ImageColor.getcolor(im, self.mode)
  716.         elif isImageType(im):
  717.             im.load()
  718.             if self.mode != im.mode:
  719.                 if self.mode != 'RGB' or im.mode not in ('RGBA', 'RGBa'):
  720.                     im = im.convert(self.mode)
  721.                 
  722.             
  723.             im = im.im
  724.         
  725.         self.load()
  726.         if self.readonly:
  727.             self._copy()
  728.         
  729.         if mask:
  730.             mask.load()
  731.             self.im.paste(im, box, mask.im)
  732.         else:
  733.             self.im.paste(im, box)
  734.  
  735.     
  736.     def point(self, lut, mode = None):
  737.         '''Map image through lookup table'''
  738.         self.load()
  739.         if not isSequenceType(lut):
  740.             if self.mode in ('I', 'I;16', 'F'):
  741.                 (scale, offset) = _getscaleoffset(lut)
  742.                 return self._new(self.im.point_transform(scale, offset))
  743.             lut = map(lut, range(256)) * self.im.bands
  744.         
  745.         if self.mode == 'F':
  746.             raise ValueError('point operation not supported for this mode')
  747.         self.mode == 'F'
  748.         return self._new(self.im.point(lut, mode))
  749.  
  750.     
  751.     def putalpha(self, alpha):
  752.         '''Set alpha layer'''
  753.         self.load()
  754.         if self.readonly:
  755.             self._copy()
  756.         
  757.         if self.mode not in ('LA', 'RGBA'):
  758.             
  759.             try:
  760.                 mode = getmodebase(self.mode) + 'A'
  761.                 
  762.                 try:
  763.                     self.im.setmode(mode)
  764.                 except (AttributeError, ValueError):
  765.                     im = self.im.convert(mode)
  766.                     if im.mode not in ('LA', 'RGBA'):
  767.                         raise ValueError
  768.                     im.mode not in ('LA', 'RGBA')
  769.                     self.im = im
  770.  
  771.                 self.mode = self.im.mode
  772.             except (KeyError, ValueError):
  773.                 raise ValueError('illegal image mode')
  774.             except:
  775.                 None<EXCEPTION MATCH>(KeyError, ValueError)
  776.             
  777.  
  778.         None<EXCEPTION MATCH>(KeyError, ValueError)
  779.         if self.mode == 'LA':
  780.             band = 1
  781.         else:
  782.             band = 3
  783.         if isImageType(alpha):
  784.             if alpha.mode not in ('1', 'L'):
  785.                 raise ValueError('illegal image mode')
  786.             alpha.mode not in ('1', 'L')
  787.             alpha.load()
  788.             if alpha.mode == '1':
  789.                 alpha = alpha.convert('L')
  790.             
  791.         else:
  792.             
  793.             try:
  794.                 self.im.fillband(band, alpha)
  795.             except (AttributeError, ValueError):
  796.                 alpha = new('L', self.size, alpha)
  797.  
  798.             return None
  799.         isImageType(alpha).im.putband(alpha.im, band)
  800.  
  801.     
  802.     def putdata(self, data, scale = 1, offset = 0):
  803.         '''Put data from a sequence object into an image.'''
  804.         self.load()
  805.         if self.readonly:
  806.             self._copy()
  807.         
  808.         self.im.putdata(data, scale, offset)
  809.  
  810.     
  811.     def putpalette(self, data, rawmode = 'RGB'):
  812.         '''Put palette data into an image.'''
  813.         self.load()
  814.         if self.mode not in ('L', 'P'):
  815.             raise ValueError('illegal image mode')
  816.         self.mode not in ('L', 'P')
  817.         if not isStringType(data):
  818.             data = string.join(map(chr, data), '')
  819.         
  820.         self.mode = 'P'
  821.         self.palette = ImagePalette.raw(rawmode, data)
  822.         self.palette.mode = 'RGB'
  823.         self.load()
  824.  
  825.     
  826.     def putpixel(self, xy, value):
  827.         '''Set pixel value'''
  828.         self.load()
  829.         if self.readonly:
  830.             self._copy()
  831.         
  832.         return self.im.putpixel(xy, value)
  833.  
  834.     
  835.     def resize(self, size, resample = NEAREST):
  836.         '''Resize image'''
  837.         if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
  838.             raise ValueError('unknown resampling filter')
  839.         resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS)
  840.         self.load()
  841.         if self.mode in ('1', 'P'):
  842.             resample = NEAREST
  843.         
  844.         if resample == ANTIALIAS:
  845.             
  846.             try:
  847.                 im = self.im.stretch(size, resample)
  848.             except AttributeError:
  849.                 raise ValueError('unsupported resampling filter')
  850.             except:
  851.                 None<EXCEPTION MATCH>AttributeError
  852.             
  853.  
  854.         None<EXCEPTION MATCH>AttributeError
  855.         im = self.im.resize(size, resample)
  856.         return self._new(im)
  857.  
  858.     
  859.     def rotate(self, angle, resample = NEAREST, expand = 0):
  860.         '''Rotate image.  Angle given as degrees counter-clockwise.'''
  861.         if expand:
  862.             import math
  863.             angle = -angle * math.pi / 180
  864.             matrix = [
  865.                 math.cos(angle),
  866.                 math.sin(angle),
  867.                 0,
  868.                 -math.sin(angle),
  869.                 math.cos(angle),
  870.                 0]
  871.             
  872.             def transform(x, y, .2 = matrix):
  873.                 (a, b, c, d, e, f) = .2
  874.                 return (a * x + b * y + c, d * x + e * y + f)
  875.  
  876.             (w, h) = self.size
  877.             xx = []
  878.             yy = []
  879.             for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
  880.                 (x, y) = transform(x, y)
  881.                 xx.append(x)
  882.                 yy.append(y)
  883.             
  884.             w = int(math.ceil(max(xx)) - math.floor(min(xx)))
  885.             h = int(math.ceil(max(yy)) - math.floor(min(yy)))
  886.             (x, y) = transform(w / 2, h / 2)
  887.             matrix[2] = self.size[0] / 2 - x
  888.             matrix[5] = self.size[1] / 2 - y
  889.             return self.transform((w, h), AFFINE, matrix)
  890.         if resample not in (NEAREST, BILINEAR, BICUBIC):
  891.             raise ValueError('unknown resampling filter')
  892.         resample not in (NEAREST, BILINEAR, BICUBIC)
  893.         self.load()
  894.         if self.mode in ('1', 'P'):
  895.             resample = NEAREST
  896.         
  897.         return self._new(self.im.rotate(angle, resample))
  898.  
  899.     
  900.     def save(self, fp, format = None, **params):
  901.         '''Save image to file or stream'''
  902.         if isStringType(fp):
  903.             filename = fp
  904.         elif hasattr(fp, 'name') and isStringType(fp.name):
  905.             filename = fp.name
  906.         else:
  907.             filename = ''
  908.         self.load()
  909.         self.encoderinfo = params
  910.         self.encoderconfig = ()
  911.         preinit()
  912.         ext = string.lower(os.path.splitext(filename)[1])
  913.         if not format:
  914.             
  915.             try:
  916.                 format = EXTENSION[ext]
  917.             except KeyError:
  918.                 init()
  919.                 
  920.                 try:
  921.                     format = EXTENSION[ext]
  922.                 except KeyError:
  923.                     raise KeyError(ext)
  924.                 except:
  925.                     None<EXCEPTION MATCH>KeyError
  926.                 
  927.  
  928.                 None<EXCEPTION MATCH>KeyError
  929.             
  930.  
  931.         None<EXCEPTION MATCH>KeyError
  932.         
  933.         try:
  934.             save_handler = SAVE[string.upper(format)]
  935.         except KeyError:
  936.             init()
  937.             save_handler = SAVE[string.upper(format)]
  938.  
  939.         if isStringType(fp):
  940.             import __builtin__
  941.             fp = __builtin__.open(fp, 'wb')
  942.             close = 1
  943.         else:
  944.             close = 0
  945.         
  946.         try:
  947.             save_handler(self, fp, filename)
  948.         finally:
  949.             if close:
  950.                 fp.close()
  951.             
  952.  
  953.  
  954.     
  955.     def seek(self, frame):
  956.         '''Seek to given frame in sequence file'''
  957.         if frame != 0:
  958.             raise EOFError
  959.         frame != 0
  960.  
  961.     
  962.     def show(self, title = None, command = None):
  963.         '''Display image (for debug purposes only)'''
  964.         _showxv(self, title, command)
  965.  
  966.     
  967.     def split(self):
  968.         '''Split image into bands'''
  969.         ims = []
  970.         self.load()
  971.         for i in range(self.im.bands):
  972.             ims.append(self._new(self.im.getband(i)))
  973.         
  974.         return tuple(ims)
  975.  
  976.     
  977.     def tell(self):
  978.         '''Return current frame number'''
  979.         return 0
  980.  
  981.     
  982.     def thumbnail(self, size, resample = NEAREST):
  983.         '''Create thumbnail representation (modifies image in place)'''
  984.         (x, y) = self.size
  985.         if x > size[0]:
  986.             y = max(y * size[0] / x, 1)
  987.             x = size[0]
  988.         
  989.         if y > size[1]:
  990.             x = max(x * size[1] / y, 1)
  991.             y = size[1]
  992.         
  993.         size = (x, y)
  994.         if size == self.size:
  995.             return None
  996.         self.draft(None, size)
  997.         self.load()
  998.         
  999.         try:
  1000.             im = self.resize(size, resample)
  1001.         except ValueError:
  1002.             size == self.size
  1003.             size == self.size
  1004.             if resample != ANTIALIAS:
  1005.                 raise 
  1006.             resample != ANTIALIAS
  1007.             im = self.resize(size, NEAREST)
  1008.         except:
  1009.             size == self.size
  1010.  
  1011.         self.im = im.im
  1012.         self.mode = im.mode
  1013.         self.size = size
  1014.         self.readonly = 0
  1015.  
  1016.     
  1017.     def transform(self, size, method, data = None, resample = NEAREST, fill = 1):
  1018.         '''Transform image'''
  1019.         import ImageTransform
  1020.         if isinstance(method, ImageTransform.Transform):
  1021.             (method, data) = method.getdata()
  1022.         
  1023.         if data is None:
  1024.             raise ValueError('missing method data')
  1025.         data is None
  1026.         im = new(self.mode, size, None)
  1027.         if method == MESH:
  1028.             for box, quad in data:
  1029.                 im._Image__transformer(box, self, QUAD, quad, resample, fill)
  1030.             
  1031.         else:
  1032.             im._Image__transformer((0, 0) + size, self, method, data, resample, fill)
  1033.         return im
  1034.  
  1035.     
  1036.     def __transformer(self, box, image, method, data, resample = NEAREST, fill = 1):
  1037.         w = box[2] - box[0]
  1038.         h = box[3] - box[1]
  1039.         if method == AFFINE:
  1040.             data = (data[2], data[0], data[1], data[5], data[3], data[4])
  1041.         elif method == EXTENT:
  1042.             (x0, y0, x1, y1) = data
  1043.             xs = float(x1 - x0) / w
  1044.             ys = float(y1 - y0) / h
  1045.             method = AFFINE
  1046.             data = (x0 + xs / 2, xs, 0, y0 + ys / 2, 0, ys)
  1047.         elif method == PERSPECTIVE:
  1048.             data = (data[2], data[0], data[1], data[5], data[3], data[4], data[6], data[7])
  1049.         elif method == QUAD:
  1050.             nw = data[0:2]
  1051.             sw = data[2:4]
  1052.             se = data[4:6]
  1053.             ne = data[6:8]
  1054.             (x0, y0) = nw
  1055.             As = 1 / w
  1056.             At = 1 / h
  1057.             data = (x0, (ne[0] - x0) * As, (sw[0] - x0) * At, ((se[0] - sw[0] - ne[0]) + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, ((se[1] - sw[1] - ne[1]) + y0) * As * At)
  1058.         else:
  1059.             raise ValueError('unknown transformation method')
  1060.         if method == AFFINE not in (NEAREST, BILINEAR, BICUBIC):
  1061.             raise ValueError('unknown resampling filter')
  1062.         method == AFFINE not in (NEAREST, BILINEAR, BICUBIC)
  1063.         image.load()
  1064.         self.load()
  1065.         if image.mode in ('1', 'P'):
  1066.             resample = NEAREST
  1067.         
  1068.         self.im.transform2(box, image.im, method, data, resample, fill)
  1069.  
  1070.     
  1071.     def transpose(self, method):
  1072.         '''Transpose image (flip or rotate in 90 degree steps)'''
  1073.         self.load()
  1074.         im = self.im.transpose(method)
  1075.         return self._new(im)
  1076.  
  1077.  
  1078.  
  1079. class _ImageCrop(Image):
  1080.     
  1081.     def __init__(self, im, box):
  1082.         Image.__init__(self)
  1083.         (x0, y0, x1, y1) = box
  1084.         if x1 < x0:
  1085.             x1 = x0
  1086.         
  1087.         if y1 < y0:
  1088.             y1 = y0
  1089.         
  1090.         self.mode = im.mode
  1091.         self.size = (x1 - x0, y1 - y0)
  1092.         self._ImageCrop__crop = (x0, y0, x1, y1)
  1093.         self.im = im.im
  1094.  
  1095.     
  1096.     def load(self):
  1097.         if self._ImageCrop__crop:
  1098.             self.im = self.im.crop(self._ImageCrop__crop)
  1099.             self._ImageCrop__crop = None
  1100.         
  1101.  
  1102.  
  1103.  
  1104. def _wedge():
  1105.     '''Create greyscale wedge (for debugging only)'''
  1106.     return Image()._new(core.wedge('L'))
  1107.  
  1108.  
  1109. def new(mode, size, color = 0):
  1110.     '''Create a new image'''
  1111.     if color is None:
  1112.         return Image()._new(core.new(mode, size))
  1113.     if isStringType(color):
  1114.         import ImageColor
  1115.         color = ImageColor.getcolor(color, mode)
  1116.     
  1117.     return Image()._new(core.fill(mode, size, color))
  1118.  
  1119.  
  1120. def fromstring(mode, size, data, decoder_name = 'raw', *args):
  1121.     '''Load image from string'''
  1122.     if len(args) == 1 and isTupleType(args[0]):
  1123.         args = args[0]
  1124.     
  1125.     if decoder_name == 'raw' and args == ():
  1126.         args = mode
  1127.     
  1128.     im = new(mode, size)
  1129.     im.fromstring(data, decoder_name, args)
  1130.     return im
  1131.  
  1132.  
  1133. def frombuffer(mode, size, data, decoder_name = 'raw', *args):
  1134.     '''Load image from string or buffer'''
  1135.     if len(args) == 1 and isTupleType(args[0]):
  1136.         args = args[0]
  1137.     
  1138.     if decoder_name == 'raw':
  1139.         if args == ():
  1140.             if warnings:
  1141.                 warnings.warn("the frombuffer defaults may change in a future release; for portability, change the call to read:\n  frombuffer(mode, size, data, 'raw', mode, 0, 1)", RuntimeWarning, stacklevel = 2)
  1142.             
  1143.             args = (mode, 0, -1)
  1144.         
  1145.         if args[0] in _MAPMODES:
  1146.             im = new(mode, (1, 1))
  1147.             im = im._new(core.map_buffer(data, size, decoder_name, None, 0, args))
  1148.             im.readonly = 1
  1149.             return im
  1150.     
  1151.     return apply(fromstring, (mode, size, data, decoder_name, args))
  1152.  
  1153.  
  1154. def fromarray(obj, mode = None):
  1155.     arr = obj.__array_interface__
  1156.     shape = arr['shape']
  1157.     ndim = len(shape)
  1158.     
  1159.     try:
  1160.         strides = arr['strides']
  1161.     except KeyError:
  1162.         strides = None
  1163.  
  1164.     if mode is None:
  1165.         typestr = arr['typestr']
  1166.         if not typestr[0] == '|' and typestr[0] == _ENDIAN or typestr[1:] not in ('u1', 'b1', 'i4', 'f4'):
  1167.             raise TypeError('cannot handle data-type')
  1168.         typestr[1:] not in ('u1', 'b1', 'i4', 'f4')
  1169.         typestr = typestr[:2]
  1170.         if typestr == 'i4':
  1171.             mode = 'I'
  1172.         elif typestr == 'f4':
  1173.             mode = 'F'
  1174.         elif typestr == 'b1':
  1175.             mode = '1'
  1176.         elif ndim == 2:
  1177.             mode = 'L'
  1178.         elif ndim == 3:
  1179.             mode = 'RGB'
  1180.         elif ndim == 4:
  1181.             mode = 'RGBA'
  1182.         else:
  1183.             raise TypeError('Do not understand data.')
  1184.     typestr == 'i4'
  1185.     ndmax = 4
  1186.     bad_dims = 0
  1187.     if mode in ('1', 'L', 'I', 'P', 'F'):
  1188.         ndmax = 2
  1189.     elif mode == 'RGB':
  1190.         ndmax = 3
  1191.     
  1192.     if ndim > ndmax:
  1193.         raise ValueError('Too many dimensions.')
  1194.     ndim > ndmax
  1195.     size = shape[:2][::-1]
  1196.     if strides is not None:
  1197.         obj = obj.tostring()
  1198.     
  1199.     return frombuffer(mode, size, obj, 'raw', mode, 0, 1)
  1200.  
  1201.  
  1202. def open(fp, mode = 'r'):
  1203.     '''Open an image file, without loading the raster data'''
  1204.     if mode != 'r':
  1205.         raise ValueError('bad mode')
  1206.     mode != 'r'
  1207.     if isStringType(fp):
  1208.         import __builtin__
  1209.         filename = fp
  1210.         fp = __builtin__.open(fp, 'rb')
  1211.     else:
  1212.         filename = ''
  1213.     prefix = fp.read(16)
  1214.     preinit()
  1215.     for i in ID:
  1216.         
  1217.         try:
  1218.             (factory, accept) = OPEN[i]
  1219.             if not accept or accept(prefix):
  1220.                 fp.seek(0)
  1221.                 return factory(fp, filename)
  1222.         continue
  1223.         except (SyntaxError, IndexError, TypeError):
  1224.             continue
  1225.         
  1226.  
  1227.     
  1228.     init()
  1229.     for i in ID:
  1230.         
  1231.         try:
  1232.             (factory, accept) = OPEN[i]
  1233.             if not accept or accept(prefix):
  1234.                 fp.seek(0)
  1235.                 return factory(fp, filename)
  1236.         continue
  1237.         except (SyntaxError, IndexError, TypeError):
  1238.             None<EXCEPTION MATCH>(SyntaxError, IndexError, TypeError)
  1239.             None<EXCEPTION MATCH>(SyntaxError, IndexError, TypeError)
  1240.             continue
  1241.         
  1242.  
  1243.     
  1244.     raise IOError('cannot identify image file')
  1245.  
  1246.  
  1247. def blend(im1, im2, alpha):
  1248.     '''Interpolate between images.'''
  1249.     im1.load()
  1250.     im2.load()
  1251.     return im1._new(core.blend(im1.im, im2.im, alpha))
  1252.  
  1253.  
  1254. def composite(image1, image2, mask):
  1255.     '''Create composite image by blending images using a transparency mask'''
  1256.     image = image2.copy()
  1257.     image.paste(image1, None, mask)
  1258.     return image
  1259.  
  1260.  
  1261. def eval(image, *args):
  1262.     '''Evaluate image expression'''
  1263.     return image.point(args[0])
  1264.  
  1265.  
  1266. def merge(mode, bands):
  1267.     '''Merge a set of single band images into a new multiband image.'''
  1268.     if getmodebands(mode) != len(bands) or '*' in mode:
  1269.         raise ValueError('wrong number of bands')
  1270.     '*' in mode
  1271.     for im in bands[1:]:
  1272.         if im.mode != getmodetype(mode):
  1273.             raise ValueError('mode mismatch')
  1274.         im.mode != getmodetype(mode)
  1275.         if im.size != bands[0].size:
  1276.             raise ValueError('size mismatch')
  1277.         im.size != bands[0].size
  1278.     
  1279.     im = core.new(mode, bands[0].size)
  1280.     for i in range(getmodebands(mode)):
  1281.         bands[i].load()
  1282.         im.putband(bands[i].im, i)
  1283.     
  1284.     return bands[0]._new(im)
  1285.  
  1286.  
  1287. def register_open(id, factory, accept = None):
  1288.     id = string.upper(id)
  1289.     ID.append(id)
  1290.     OPEN[id] = (factory, accept)
  1291.  
  1292.  
  1293. def register_mime(id, mimetype):
  1294.     MIME[string.upper(id)] = mimetype
  1295.  
  1296.  
  1297. def register_save(id, driver):
  1298.     SAVE[string.upper(id)] = driver
  1299.  
  1300.  
  1301. def register_extension(id, extension):
  1302.     EXTENSION[string.lower(extension)] = string.upper(id)
  1303.  
  1304.  
  1305. def _showxv(image, title = None, command = None):
  1306.     if os.name == 'nt':
  1307.         format = 'BMP'
  1308.     elif sys.platform == 'darwin':
  1309.         format = 'JPEG'
  1310.         if not command:
  1311.             command = 'open -a /Applications/Preview.app'
  1312.         
  1313.     else:
  1314.         format = None
  1315.         if not command:
  1316.             for cmd in [
  1317.                 'eog',
  1318.                 'gqview',
  1319.                 'gwenview',
  1320.                 'xv']:
  1321.                 if _iscommand(cmd):
  1322.                     command = cmd
  1323.                     break
  1324.                     continue
  1325.             
  1326.             if not command:
  1327.                 print 'no image viewer found'
  1328.             
  1329.             if command in 'xv' and title:
  1330.                 command = command + ' -name "%s"' % title
  1331.             
  1332.         
  1333.     if image.mode == 'I;16':
  1334.         base = 'L'
  1335.     else:
  1336.         base = getmodebase(image.mode)
  1337.     if base != image.mode and image.mode != '1':
  1338.         file = image.convert(base)._dump(format = format)
  1339.     else:
  1340.         file = image._dump(format = format)
  1341.     if os.name == 'nt':
  1342.         command = 'start /wait %s && del /f %s' % (file, file)
  1343.     elif sys.platform == 'darwin':
  1344.         command = '(%s %s; sleep 20; rm -f %s)&' % (command, file, file)
  1345.     else:
  1346.         command = '(%s %s; rm -f %s)&' % (command, file, file)
  1347.     os.system(command)
  1348.  
  1349.  
  1350. def _isexecutable(cmd):
  1351.     if os.path.isfile(cmd):
  1352.         mode = os.stat(cmd)[stat.ST_MODE]
  1353.         if mode & stat.S_IXUSR and mode & stat.S_IXGRP or mode & stat.S_IXOTH:
  1354.             return True
  1355.     
  1356.     return False
  1357.  
  1358.  
  1359. def _iscommand(cmd):
  1360.     '''Return True if cmd is executable or can be found on the executable
  1361.     search path.'''
  1362.     if _isexecutable(cmd):
  1363.         return True
  1364.     path = os.environ.get('PATH')
  1365.     if not path:
  1366.         return False
  1367.     for d in path.split(os.pathsep):
  1368.         exe = os.path.join(d, cmd)
  1369.         if _isexecutable(exe):
  1370.             return True
  1371.     
  1372.     return False
  1373.  
  1374.