~ubuntu-branches/ubuntu/saucy/python-imaging/saucy-proposed

« back to all changes in this revision

Viewing changes to .pc/git-updates.diff/PIL/Image.py

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-03-20 16:44:01 UTC
  • mfrom: (2.1.13 experimental)
  • Revision ID: package-import@ubuntu.com-20130320164401-ptf6m0ttg4zw72az
Tags: 1.1.7+2.0.0-1
Pillow 2.0.0 release.

Show diffs side-by-side

added added

removed removed

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