~ubuntu-branches/debian/squeeze/python-imaging/squeeze

« back to all changes in this revision

Viewing changes to PIL/Image.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2006-08-28 23:14:10 UTC
  • mfrom: (2.1.5 edgy)
  • Revision ID: james.westby@ubuntu.com-20060828231410-lca9enmne3ecmkup
Tags: 1.1.5-11
* python-imaging-sane: Depend on python-numarray. Closes: #382190.
* Add dependencies on ${shlibs:Depends}, lost in -6. Closes: #378596.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#
2
2
# The Python Imaging Library.
3
 
# $Id: //modules/pil/PIL/Image.py#47 $
 
3
# $Id: Image.py 2337 2005-03-25 07:50:30Z fredrik $
4
4
#
5
5
# the Image class wrapper
6
6
#
8
8
# 1995-09-09 fl   Created
9
9
# 1996-03-11 fl   PIL release 0.0 (proof of concept)
10
10
# 1996-04-30 fl   PIL release 0.1b1
11
 
# 1996-05-27 fl   PIL release 0.1b2
12
 
# 1996-11-04 fl   PIL release 0.2b1
13
 
# 1996-12-08 fl   PIL release 0.2b2
14
 
# 1996-12-16 fl   PIL release 0.2b3
15
 
# 1997-01-14 fl   PIL release 0.2b4
16
 
# 1998-07-02 fl   PIL release 0.3b1
17
 
# 1998-07-17 fl   PIL release 0.3b2
18
 
# 1999-01-01 fl   PIL release 1.0b1
19
 
# 1999-02-08 fl   PIL release 1.0b2
20
11
# 1999-07-28 fl   PIL release 1.0 final
21
12
# 2000-06-07 fl   PIL release 1.1
22
13
# 2000-10-20 fl   PIL release 1.1.1
23
14
# 2001-05-07 fl   PIL release 1.1.2
24
 
# 2002-01-14 fl   PIL release 1.2b1 (imToolkit)
25
15
# 2002-03-15 fl   PIL release 1.1.3
26
16
# 2003-05-10 fl   PIL release 1.1.4
 
17
# 2005-03-28 fl   PIL release 1.1.5
27
18
#
28
 
# Copyright (c) 1997-2003 by Secret Labs AB.  All rights reserved.
29
 
# Copyright (c) 1995-2003 by Fredrik Lundh.
 
19
# Copyright (c) 1997-2005 by Secret Labs AB.  All rights reserved.
 
20
# Copyright (c) 1995-2005 by Fredrik Lundh.
30
21
#
31
22
# See the README file for information on usage and redistribution.
32
23
#
33
24
 
34
 
VERSION = "1.1.4"
 
25
VERSION = "1.1.5"
 
26
 
 
27
try:
 
28
    import warnings
 
29
except ImportError:
 
30
    warnings = None
35
31
 
36
32
class _imaging_not_installed:
37
33
    # module placeholder
40
36
 
41
37
try:
42
38
    # give Tk a chance to set up the environment, in case we're
43
 
    # using an _imaging module linked against libtcl/libtk
44
 
    import FixTk
 
39
    # using an _imaging module linked against libtcl/libtk (use
 
40
    # __import__ to hide this from naive packagers; we don't really
 
41
    # depend on Tk unless ImageTk is used, and that module already
 
42
    # imports Tkinter)
 
43
    __import__("FixTk")
45
44
except ImportError:
46
45
    pass
47
46
 
54
53
    core = _imaging
55
54
    del _imaging
56
55
except ImportError, v:
57
 
    import string
58
56
    core = _imaging_not_installed()
59
 
    if str(v)[:20] == "Module use of python":
 
57
    if str(v)[:20] == "Module use of python" and warnings:
60
58
        # The _imaging C module is present, but not compiled for
61
59
        # the right version (windows only).  Print a warning, if
62
60
        # possible.
63
 
        try:
64
 
            import warnings
65
 
            warnings.warn(
66
 
                "The _imaging extension was built for another version "
67
 
                "of Python; most PIL functions will be disabled",
68
 
                RuntimeWarning
69
 
                )
70
 
        except (ImportError, NameError, AttributeError):
71
 
            pass # sorry
 
61
        warnings.warn(
 
62
            "The _imaging extension was built for another version "
 
63
            "of Python; most PIL functions will be disabled",
 
64
            RuntimeWarning
 
65
            )
72
66
 
73
67
import ImagePalette
74
68
import os, string, sys
78
72
 
79
73
try:
80
74
    UnicodeStringType = type(unicode(""))
 
75
    ##
 
76
    # (Internal) Checks if an object is a string.  If the current
 
77
    # Python version supports Unicode, this checks for both 8-bit
 
78
    # and Unicode strings.
81
79
    def isStringType(t):
82
80
        return isinstance(t, StringType) or isinstance(t, UnicodeStringType)
83
81
except NameError:
84
82
    def isStringType(t):
85
83
        return isinstance(t, StringType)
86
84
 
 
85
##
 
86
# (Internal) Checks if an object is a tuple.
 
87
 
87
88
def isTupleType(t):
88
89
    return isinstance(t, TupleType)
89
90
 
 
91
##
 
92
# (Internal) Checks if an object is an image object.
 
93
 
90
94
def isImageType(t):
91
95
    return hasattr(t, "im")
92
96
 
 
97
##
 
98
# (Internal) Checks if an object is a string, and that it points to a
 
99
# directory.
 
100
 
93
101
def isDirectory(f):
94
102
    return isStringType(f) and os.path.isdir(f)
95
103
 
115
123
# transforms
116
124
AFFINE = 0
117
125
EXTENT = 1
118
 
PERSPECTIVE = 2 # Not yet implemented
 
126
PERSPECTIVE = 2
119
127
QUAD = 3
120
128
MESH = 4
121
129
 
182
190
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16B")
183
191
 
184
192
##
185
 
# Get "base" mode.  Given a mode, this function returns "L" for
 
193
# Gets the "base" mode for given mode.  This function returns "L" for
186
194
# images that contain grayscale data, and "RGB" for images that
187
195
# contain color data.
188
196
#
189
197
# @param mode Input mode.
190
198
# @return "L" or "RGB".
191
 
# @exception KeyError The input mode was not a standard mode.
 
199
# @exception KeyError If the input mode was not a standard mode.
192
200
 
193
201
def getmodebase(mode):
194
202
    # corresponding "base" mode (grayscale or colour)
 
203
    if mode == "LA":
 
204
        return "L"
 
205
    if mode == "PA":
 
206
        return "RGB"
195
207
    return _MODEINFO[mode][0]
196
208
 
197
209
##
198
 
# Get storage type mode.  Given a mode, this function returns a
 
210
# Gets the storage type mode.  Given a mode, this function returns a
199
211
# single-layer mode suitable for storing individual bands.
200
212
#
201
213
# @param mode Input mode.
202
214
# @return "L", "I", or "F".
203
 
# @exception KeyError The input mode was not a standard mode.
 
215
# @exception KeyError If the input mode was not a standard mode.
204
216
 
205
217
def getmodetype(mode):
206
218
    # storage type (per band)
 
219
    if mode == "LA":
 
220
        return "L"
 
221
    if mode == "PA":
 
222
        return "L"
207
223
    return _MODEINFO[mode][1]
208
224
 
209
225
##
210
 
 
211
 
# Get list of individual band names.  Given a mode, this function
 
226
# Gets a list of individual band names.  Given a mode, this function
212
227
# returns a tuple containing the names of individual bands (use
213
 
# <b>getmodetype</b> to get the mode used to store each individual
 
228
# {@link #getmodetype} to get the mode used to store each individual
214
229
# band.
215
230
#
216
231
# @param mode Input mode.
217
232
# @return A tuple containing band names.  The length of the tuple
218
233
#     gives the number of bands in an image of the given mode.
219
 
# @exception KeyError The input mode was not a standard mode.
220
 
 
 
234
# @exception KeyError If the input mode was not a standard mode.
221
235
 
222
236
def getmodebands(mode):
223
237
    # return list of subcomponents
 
238
    if mode == "LA":
 
239
        return "L", "A"
 
240
    if mode == "PA":
 
241
        return "P", "A"
224
242
    return len(_MODEINFO[mode][2])
225
243
 
226
244
# --------------------------------------------------------------------
229
247
_initialized = 0
230
248
 
231
249
##
232
 
# Explicitly load standard file format drivers.
 
250
# Explicitly loads standard file format drivers.
233
251
 
234
252
def preinit():
235
253
    "Load standard file format drivers."
247
265
    _initialized = 1
248
266
 
249
267
##
250
 
# Explicitly load all available file format drivers.
 
268
# Explicitly initializes the Python Imaging Library.  This function
 
269
# loads all available file format drivers.
251
270
 
252
271
def init():
253
272
    "Load all file format drivers."
470
489
                "static char %s_bits[] = {\n" % name, data, "};"], "")
471
490
 
472
491
    ##
473
 
    # Same as the <b>fromstring</b> function, but loads data
474
 
    # into the current image.
 
492
    # Loads this image with pixel data from a string.
 
493
    # <p>
 
494
    # This method is similar to the {@link #fromstring} function, but
 
495
    # loads data into this image instead of creating a new image
 
496
    # object.
475
497
 
476
498
    def fromstring(self, data, decoder_name="raw", *args):
477
499
        "Load data to image from binary string"
513
535
                self.palette.mode = "RGBA"
514
536
 
515
537
    ##
516
 
    # Verify file contents. For data read from a file, this method
517
 
    # attempts to determine if the file is broken, without actually
518
 
    # decoding the image data.  If this method finds any problems, it
519
 
    # raises suitable exceptions.  If you need to load the image after
520
 
    # using this method, you must reopen the image file.
 
538
    # Verifies the contents of a file. For data read from a file, this
 
539
    # method attempts to determine if the file is broken, without
 
540
    # actually decoding the image data.  If this method finds any
 
541
    # problems, it raises suitable exceptions.  If you need to load
 
542
    # the image after using this method, you must reopen the image
 
543
    # file.
521
544
 
522
545
    def verify(self):
523
546
        "Verify file contents."
525
548
 
526
549
 
527
550
    ##
528
 
    # Returns a converted copy of an image. For the "P" mode, this
529
 
    # translates pixels through the palette. If mode is omitted, a
530
 
    # mode is chosen so that all information in the image and the
531
 
    # palette can be represented without a palette.
 
551
    # Returns a converted copy of this image. For the "P" mode, this
 
552
    # method translates pixels through the palette.  If mode is
 
553
    # omitted, a mode is chosen so that all information in the image
 
554
    # and the palette can be represented without a palette.
532
555
    # <p>
533
556
    # The current version supports all possible conversions between
534
557
    # "L", "RGB" and "CMYK."
540
563
    # <p>
541
564
    # When translating a greyscale image into a bilevel image (mode
542
565
    # "1"), all non-zero values are set to 255 (white). To use other
543
 
    # thresholds, use the <b>point</b> method.
 
566
    # thresholds, use the {@link #Image.point} method.
544
567
    #
545
568
    # @def convert(mode, matrix=None)
546
569
    # @param mode The requested mode.
599
622
        #    1 = maximum coverage
600
623
 
601
624
        # NOTE: this functionality will be moved to the extended
602
 
        # quantizer interface in a later versions of PIL.
 
625
        # quantizer interface in a later version of PIL.
603
626
 
604
627
        self.load()
605
628
 
619
642
        return self._new(im)
620
643
 
621
644
    ##
622
 
    # Copies the image. Use this method if you wish to paste things
 
645
    # Copies this image. Use this method if you wish to paste things
623
646
    # into an image, but still retain the original.
624
647
    #
625
648
    # @return An Image object.
632
655
        return self._new(im)
633
656
 
634
657
    ##
635
 
    # Returns a rectangular region from the current image. The box is
636
 
    # a 4-tuple defining the left, upper, right, and lower pixel
 
658
    # Returns a rectangular region from this image. The box is a
 
659
    # 4-tuple defining the left, upper, right, and lower pixel
637
660
    # coordinate.
638
661
    # <p>
639
662
    # This is a lazy operation.  Changes to the source image may or
640
663
    # may not be reflected in the cropped image.  To break the
641
 
    # connection, call the <b>load</b> method on the cropped copy.
 
664
    # connection, call the {@link #Image.load} method on the cropped
 
665
    # copy.
642
666
    #
 
667
    # @param The crop rectangle, as a (left, upper, right, lower)-tuple.
643
668
    # @return An Image object.
644
669
 
645
670
    def crop(self, box=None):
670
695
 
671
696
        pass
672
697
 
 
698
    def _expand(self, xmargin, ymargin=None):
 
699
        if ymargin is None:
 
700
            ymargin = xmargin
 
701
        self.load()
 
702
        return self._new(self.im.expand(xmargin, ymargin, 0))
 
703
 
673
704
    ##
674
 
    # Filter image by the given filter.  For a list of available
675
 
    # filters, see the <b>ImageFilter</b> module.
 
705
    # Filters this image using the given filter.  For a list of
 
706
    # available filters, see the <b>ImageFilter</b> module.
676
707
    #
677
708
    # @param filter Filter kernel.
678
709
    # @return An Image object.
696
727
        return merge(self.mode, ims)
697
728
 
698
729
    ##
699
 
    # Returns a tuple containing the name of each band. For example,
700
 
    # <b>getbands</b> on an RGB image returns ("R", "G", "B").
 
730
    # Returns a tuple containing the name of each band in this image.
 
731
    # For example, <b>getbands</b> on an RGB image returns ("R", "G", "B").
701
732
    #
702
733
    # @return A tuple containing band names.
703
734
 
709
740
    ##
710
741
    # Calculates the bounding box of the non-zero regions in the
711
742
    # image.
 
743
    #
712
744
    # @return The bounding box is returned as a 4-tuple defining the
713
745
    #    left, upper, right, and lower pixel coordinate. If the image
714
746
    #    is completely empty, this method returns None.
720
752
        return self.im.getbbox()
721
753
 
722
754
    ##
723
 
    # Returns the contents of an image as a sequence object containing
724
 
    # pixel values.  The sequence object is flattened, so that values
725
 
    # for line one follow directly after the values of line zero, and
726
 
    # so on.
 
755
    # Returns a list of colors used in this image.
 
756
    #
 
757
    # @param maxcolors Maximum number of colors.  If this number is
 
758
    #    exceeded, this method returns None.  The default limit is
 
759
    #    256 colors.
 
760
    # @return An unsorted list of (count, pixel) values.
 
761
 
 
762
    def getcolors(self, maxcolors=256):
 
763
        "Get colors from image, up to given limit"
 
764
 
 
765
        self.load()
 
766
        if self.mode in ("1", "L", "P"):
 
767
            h = self.im.histogram()
 
768
            out = []
 
769
            for i in range(256):
 
770
                if h[i]:
 
771
                    out.append((h[i], i))
 
772
            if len(out) > maxcolors:
 
773
                return None
 
774
            return out
 
775
        return self.im.getcolors(maxcolors)
 
776
 
 
777
    ##
 
778
    # Returns the contents of this image as a sequence object
 
779
    # containing pixel values.  The sequence object is flattened, so
 
780
    # that values for line one follow directly after the values of
 
781
    # line zero, and so on.
727
782
    # <p>
728
783
    # Note that the sequence object returned by this method is an
729
784
    # internal PIL data type, which only supports certain sequence
744
799
        return self.im # could be abused
745
800
 
746
801
    ##
747
 
    # Get the the minimum and maximum pixel values for each band in
 
802
    # Gets the the minimum and maximum pixel values for each band in
748
803
    # the image.
749
804
    #
750
805
    # @return For a single-band image, a 2-tuple containing the
763
818
        return self.im.getextrema()
764
819
 
765
820
    ##
 
821
    # Returns a PyCObject that points to the internal image memory.
 
822
    #
 
823
    # @return A PyCObject object.
 
824
 
 
825
    def getim(self):
 
826
        "Get PyCObject pointer to internal image memory"
 
827
 
 
828
        self.load()
 
829
        return self.im.ptr
 
830
 
 
831
 
 
832
    ##
 
833
    # Returns the image palette as a list.
 
834
    #
 
835
    # @return A list of color values [r, g, b, ...], or None if the
 
836
    #    image has no palette.
 
837
 
 
838
    def getpalette(self):
 
839
        "Get palette contents."
 
840
 
 
841
        self.load()
 
842
        try:
 
843
            return map(ord, self.im.getpalette())
 
844
        except ValueError:
 
845
            return None # no palette
 
846
 
 
847
 
 
848
    ##
766
849
    # Returns the pixel value at a given position.
767
850
    #
768
851
    # @param xy The coordinate, given as (x, y).
775
858
        self.load()
776
859
        return self.im.getpixel(xy)
777
860
 
 
861
    ##
 
862
    # Returns the horizontal and vertical projection.
 
863
    #
 
864
    # @return Two sequences, indicating where there are non-zero
 
865
    #     pixels along the X-axis and the Y-axis, respectively.
 
866
 
778
867
    def getprojection(self):
779
868
        "Get projection to x and y axes"
780
869
 
829
918
 
830
919
    def offset(self, xoffset, yoffset=None):
831
920
        "(deprecated) Offset image in horizontal and/or vertical direction"
 
921
        if warnings:
 
922
            warnings.warn(
 
923
                "'offset' is deprecated; use 'ImageChops.offset' instead",
 
924
               DeprecationWarning
 
925
                )
832
926
        import ImageChops
833
927
        return ImageChops.offset(self, xoffset, yoffset)
834
928
 
840
934
    # must match the size of the region.
841
935
    # <p>
842
936
    # If the modes don't match, the pasted image is converted to the
843
 
    # mode of this image (see the <b>convert</b> method for details).
 
937
    # mode of this image (see the {@link #Image.convert} method for
 
938
    # details).
844
939
    # <p>
845
940
    # Instead of an image, the source can be a integer or tuple
846
941
    # containing pixel values.  The method then fills the region
859
954
    # both source image and mask.
860
955
    #
861
956
    # @param im Source image or pixel value (integer or tuple).
862
 
    # @param box A 4-tuple giving the region to paste into.  If a
863
 
    #    2-tuple is used instead, it's treated as the upper left
864
 
    #    corner.  If None is used instead, the source is pasted
865
 
    #    into the upper left corner.
 
957
    # @param box An optional 4-tuple giving the region to paste into.
 
958
    #    If a 2-tuple is used instead, it's treated as the upper left
 
959
    #    corner.  If omitted or None, the source is pasted into the
 
960
    #    upper left corner.
 
961
    #    <p>
 
962
    #    If an image is given as the second argument and there is no
 
963
    #    third, the box defaults to (0, 0), and the second argument
 
964
    #    is interpreted as a mask image.
866
965
    # @param mask An optional mask image.
867
966
    # @return An Image object.
868
967
 
869
968
    def paste(self, im, box=None, mask=None):
870
969
        "Paste other image into region"
871
970
 
 
971
        if isImageType(box) and mask is None:
 
972
            # abbreviated paste(im, mask) syntax
 
973
            mask = box; box = None
 
974
 
872
975
        if box is None:
873
976
            # cover all of self
874
977
            box = (0, 0) + self.size
876
979
        if len(box) == 2:
877
980
            # lower left corner given; get size from image or mask
878
981
            if isImageType(im):
879
 
                box = box + (box[0]+im.size[0], box[1]+im.size[1])
 
982
                size = im.size
 
983
            elif isImageType(mask):
 
984
                size = mask.size
880
985
            else:
881
 
                box = box + (box[0]+mask.size[0], box[1]+mask.size[1])
 
986
                # FIXME: use self.size here?
 
987
                raise ValueError(
 
988
                    "cannot determine region size; use 4-item box"
 
989
                    )
 
990
            box = box + (box[0]+size[0], box[1]+size[1])
882
991
 
883
992
        if isStringType(im):
884
993
            import ImageColor
904
1013
            self.im.paste(im, box)
905
1014
 
906
1015
    ##
907
 
    # Map image through lookup table or function.
 
1016
    # Maps this image through a lookup table or function.
908
1017
    #
909
1018
    # @param lut A lookup table, containing 256 values per band in the
910
1019
    #    image. A function can be used instead, it should take a single
919
1028
    def point(self, lut, mode=None):
920
1029
        "Map image through lookup table"
921
1030
 
922
 
        if self.mode in ("I", "I;16", "F"):
923
 
            # floating point; lut must be a valid expression
924
 
            scale, offset = _getscaleoffset(lut)
925
 
            self.load()
926
 
            im = self.im.point_transform(scale, offset);
927
 
        else:
928
 
            # integer image; use lut and mode
929
 
            self.load()
930
 
            if not isSequenceType(lut):
931
 
                # if it isn't a list, it should be a function
932
 
                lut = map(lut, range(256)) * self.im.bands
933
 
            im = self.im.point(lut, mode)
934
 
 
935
 
        return self._new(im)
 
1031
        if not isSequenceType(lut):
 
1032
            # if it isn't a list, it should be a function
 
1033
            if self.mode in ("I", "I;16", "F"):
 
1034
                # check if the function can be used with point_transform
 
1035
                scale, offset = _getscaleoffset(lut)
 
1036
                self.load()
 
1037
                return self._new(self.im.point_transform(scale, offset))
 
1038
            # for other modes, convert the function to a table
 
1039
            lut = map(lut, range(256)) * self.im.bands
 
1040
 
 
1041
        if self.mode == "F":
 
1042
            # FIXME: _imaging returns a confusing error message for this case
 
1043
            raise ValueError("point operation not supported for this mode")
 
1044
 
 
1045
        self.load()
 
1046
        return self._new(self.im.point(lut, mode))
936
1047
 
937
1048
    ##
938
 
    # Replace the alpha layer in the current image.  The image must be
939
 
    # an "RGBA" image, and the band must be either "L" or "1".
 
1049
    # Adds or replaces the alpha layer in this image.  If the image
 
1050
    # does not have an alpha layer, it's converted to "LA" or "RGBA".
 
1051
    # The new layer must be either "L" or "1".
940
1052
    #
941
 
    # @param im The new alpha layer.
 
1053
    # @param im The new alpha layer.  This can either be an "L" or "1"
 
1054
    #    image having the same size as this image, or an integer or
 
1055
    #    other color value.
942
1056
 
943
 
    def putalpha(self, im):
 
1057
    def putalpha(self, alpha):
944
1058
        "Set alpha layer"
945
1059
 
946
 
        if self.mode != "RGBA" or im.mode not in ("1", "L"):
947
 
            raise ValueError("illegal image mode")
948
 
 
949
 
        im.load()
950
1060
        self.load()
951
1061
 
952
 
        if im.mode == "1":
953
 
            im = im.convert("L")
954
 
 
955
 
        self.im.putband(im.im, 3)
 
1062
        if self.readonly:
 
1063
            self._copy()
 
1064
 
 
1065
        if self.mode not in ("LA", "RGBA"):
 
1066
            # attempt to promote self to a matching alpha mode
 
1067
            try:
 
1068
                mode = getmodebase(self.mode) + "A"
 
1069
                try:
 
1070
                    self.im.setmode(mode)
 
1071
                except (AttributeError, ValueError):
 
1072
                    # do things the hard way
 
1073
                    im = self.im.convert(mode)
 
1074
                    if im.mode not in ("LA", "RGBA"):
 
1075
                        raise ValueError # sanity check
 
1076
                    self.im = im
 
1077
                self.mode = self.im.mode
 
1078
            except (KeyError, ValueError):
 
1079
                raise ValueError("illegal image mode")
 
1080
 
 
1081
        if self.mode == "LA":
 
1082
            band = 1
 
1083
        else:
 
1084
            band = 3
 
1085
 
 
1086
        if isImageType(alpha):
 
1087
            # alpha layer
 
1088
            if alpha.mode not in ("1", "L"):
 
1089
                raise ValueError("illegal image mode")
 
1090
            alpha.load()
 
1091
            if alpha.mode == "1":
 
1092
                alpha = alpha.convert("L")
 
1093
        else:
 
1094
            # constant alpha
 
1095
            try:
 
1096
                self.im.fillband(band, alpha)
 
1097
            except (AttributeError, ValueError):
 
1098
                # do things the hard way
 
1099
                alpha = new("L", self.size, alpha)
 
1100
            else:
 
1101
                return
 
1102
 
 
1103
        self.im.putband(alpha.im, band)
956
1104
 
957
1105
    ##
958
 
    # Copy pixel data to this image.  This method copies data from a
 
1106
    # Copies pixel data to this image.  This method copies data from a
959
1107
    # sequence object into the image, starting at the upper left
960
1108
    # corner (0, 0), and continuing until either the image or the
961
1109
    # sequence ends.  The scale and offset values are used to adjust
972
1120
        self.im.putdata(data, scale, offset)
973
1121
 
974
1122
    ##
975
 
    # Attach a palette to a "P" or "L" image. The palette sequence
976
 
    # should contain 768 integer values, where each group of three
977
 
    # values represent the red, green, and blue values for the
978
 
    # corresponding pixel index. Instead of an integer sequence, you
979
 
    # can use an 8-bit string.
 
1123
    # Attaches a palette to this image.  The image must be a "P" or
 
1124
    # "L" image, and the palette sequence must contain 768 integer
 
1125
    # values, where each group of three values represent the red,
 
1126
    # green, and blue values for the corresponding pixel
 
1127
    # index. Instead of an integer sequence, you can use an 8-bit
 
1128
    # string.
980
1129
    #
981
1130
    # @def putpalette(data)
982
 
    # @param data A palette sequence.
 
1131
    # @param data A palette sequence (either a list or a string).
983
1132
 
984
1133
    def putpalette(self, data, rawmode="RGB"):
985
1134
        "Put palette data into an image."
1000
1149
    # multi-band images.
1001
1150
    # <p>
1002
1151
    # Note that this method is relatively slow.  For more extensive
1003
 
    # changes, use <b>paste</b> or the <b>ImageDraw</b> module
 
1152
    # changes, use {@link #Image.paste} or the <b>ImageDraw</b> module
1004
1153
    # instead.
1005
1154
    #
1006
1155
    # @param xy The pixel coordinate, given as (x, y).
1016
1165
        return self.im.putpixel(xy, value)
1017
1166
 
1018
1167
    ##
1019
 
    # Returns a resized copy of an image.
 
1168
    # Returns a resized copy of this image.
1020
1169
    #
1021
1170
    # @def resize(size, filter=NEAREST)
1022
1171
    # @param size The requested size in pixels, as a 2-tuple:
1053
1202
        return self._new(im)
1054
1203
 
1055
1204
    ##
1056
 
    # Returns a rotated image.  This method returns a copy of an
1057
 
    # image, rotated the given number of degrees counter clockwise
1058
 
    # around its centre.
 
1205
    # Returns a rotated copy of this image.  This method returns a
 
1206
    # copy of this image, rotated the given number of degrees counter
 
1207
    # clockwise around its centre.
1059
1208
    #
1060
1209
    # @def rotate(angle, filter=NEAREST)
1061
1210
    # @param angle In degrees counter clockwise.
1081
1230
        return self._new(self.im.rotate(angle, resample))
1082
1231
 
1083
1232
    ##
1084
 
    # Saves the image under the given filename.  If no format is
 
1233
    # Saves this image under the given filename.  If no format is
1085
1234
    # specified, the format to use is determined from the filename
1086
1235
    # extension, if possible.
1087
1236
    # <p>
1103
1252
    #    parameter should always be used.
1104
1253
    # @param **options Extra parameters to the image writer.
1105
1254
    # @return None
 
1255
    # @exception KeyError If the output format could not be determined
 
1256
    #    from the file name.  Use the format option to solve this.
 
1257
    # @exception IOError If the file could not be written.  The file
 
1258
    #    may have been created, and may contain partial data.
1106
1259
 
1107
1260
    def save(self, fp, format=None, **params):
1108
1261
        "Save image to file or stream"
1109
1262
 
1110
1263
        if isStringType(fp):
1111
 
            import __builtin__
1112
1264
            filename = fp
1113
 
            fp = __builtin__.open(fp, "wb")
1114
 
            close = 1
1115
1265
        else:
1116
1266
            if hasattr(fp, "name") and isStringType(fp.name):
1117
1267
                filename = fp.name
1118
1268
            else:
1119
1269
                filename = ""
1120
 
            close = 0
 
1270
 
 
1271
        # may mutate self!
 
1272
        self.load()
1121
1273
 
1122
1274
        self.encoderinfo = params
1123
1275
        self.encoderconfig = ()
1124
1276
 
1125
 
        self.load()
1126
 
 
1127
1277
        preinit()
1128
1278
 
1129
1279
        ext = string.lower(os.path.splitext(filename)[1])
1130
1280
 
 
1281
        if not format:
 
1282
            try:
 
1283
                format = EXTENSION[ext]
 
1284
            except KeyError:
 
1285
                init()
 
1286
                try:
 
1287
                    format = EXTENSION[ext]
 
1288
                except KeyError:
 
1289
                    raise KeyError(ext) # unknown extension
 
1290
 
1131
1291
        try:
1132
 
 
1133
 
            if not format:
1134
 
                format = EXTENSION[ext]
1135
 
 
1136
 
            SAVE[string.upper(format)](self, fp, filename)
1137
 
 
1138
 
        except KeyError, v:
1139
 
 
 
1292
            save_handler = SAVE[string.upper(format)]
 
1293
        except KeyError:
1140
1294
            init()
1141
 
 
1142
 
            if not format:
1143
 
                format = EXTENSION[ext]
1144
 
 
1145
 
            SAVE[string.upper(format)](self, fp, filename)
1146
 
 
1147
 
        if close:
1148
 
            fp.close()
 
1295
            save_handler = SAVE[string.upper(format)] # unknown format
 
1296
 
 
1297
        if isStringType(fp):
 
1298
            import __builtin__
 
1299
            fp = __builtin__.open(fp, "wb")
 
1300
            close = 1
 
1301
        else:
 
1302
            close = 0
 
1303
 
 
1304
        try:
 
1305
            save_handler(self, fp, filename)
 
1306
        finally:
 
1307
            # do what we can to clean up
 
1308
            if close:
 
1309
                fp.close()
1149
1310
 
1150
1311
    ##
1151
 
    # Seeks to the given frame in a sequence file. If you seek beyond
1152
 
    # the end of the sequence, the method raises an <b>EOFError</b>
1153
 
    # exception. When a sequence file is opened, the library
1154
 
    # automatically seeks to frame 0.
 
1312
    # Seeks to the given frame in this sequence file. If you seek
 
1313
    # beyond the end of the sequence, the method raises an
 
1314
    # <b>EOFError</b> exception. When a sequence file is opened, the
 
1315
    # library automatically seeks to frame 0.
1155
1316
    # <p>
1156
1317
    # Note that in the current version of the library, most sequence
1157
1318
    # formats only allows you to seek to the next frame.
1158
1319
    #
1159
1320
    # @param frame Frame number, starting at 0.
1160
 
    # @exception EOFError Attempt to seek beyond the end of the sequence.
 
1321
    # @exception EOFError If the call attempts to seek beyond the end
 
1322
    #     of the sequence.
1161
1323
    # @see #Image.tell
1162
1324
 
1163
1325
    def seek(self, frame):
1168
1330
            raise EOFError
1169
1331
 
1170
1332
    ##
1171
 
    # Displays an image. This method is mainly intended for
 
1333
    # Displays this image. This method is mainly intended for
1172
1334
    # debugging purposes.
1173
1335
    # <p>
1174
1336
    # On Unix platforms, this method saves the image to a temporary
1184
1346
    def show(self, title=None, command=None):
1185
1347
        "Display image (for debug purposes only)"
1186
1348
 
1187
 
        try:
1188
 
            import ImageTk
1189
 
            ImageTk._show(self, title)
1190
 
            # note: caller must enter mainloop!
1191
 
        except:
1192
 
            _showmime(self, title, command)
 
1349
        _showxv(self, title, command)
1193
1350
 
1194
1351
    ##
1195
 
    # Split image into individual bands. This methods returns a tuple
1196
 
    # of individual image bands from an image. For example, splitting
1197
 
    # an "RGB" image creates three new images each containing a copy
1198
 
    # of one of the original bands (red, green, blue).
 
1352
    # Split this image into individual bands. This method returns a
 
1353
    # tuple of individual image bands from an image. For example,
 
1354
    # splitting an "RGB" image creates three new images each
 
1355
    # containing a copy of one of the original bands (red, green,
 
1356
    # blue).
1199
1357
    #
1200
1358
    # @return A tuple containing bands.
1201
1359
 
1220
1378
        return 0
1221
1379
 
1222
1380
    ##
1223
 
    # Make thumbnail.  This method modifies the image to contain a
1224
 
    # thumbnail version of itself, no larger than the given size.
1225
 
    # This method calculates an appropriate thumbnail size to preserve
1226
 
    # the aspect of the image, calls the <b>draft</b> method to
1227
 
    # configure the file reader (where applicable), and finally
1228
 
    # resizes the image.
 
1381
    # Make this image into a thumbnail.  This method modifies the
 
1382
    # image to contain a thumbnail version of itself, no larger than
 
1383
    # the given size.  This method calculates an appropriate thumbnail
 
1384
    # size to preserve the aspect of the image, calls the {@link
 
1385
    # #Image.draft} method to configure the file reader (where
 
1386
    # applicable), and finally resizes the image.
1229
1387
    # <p>
1230
1388
    # Note that the bilinear and bicubic filters in the current
1231
1389
    # version of PIL are not well-suited for thumbnail generation.
1234
1392
    # <p>
1235
1393
    # Also note that this function modifies the Image object in place.
1236
1394
    # If you need to use the full resolution image as well, apply this
1237
 
    # method to a <b>copy</b> of the original image.
 
1395
    # method to a {@link #Image.copy} of the original image.
1238
1396
    #
1239
1397
    # @param size Requested size.
1240
1398
    # @param resample Optional resampling filter.  This can be one
1241
1399
    #    of <b>NEAREST</b>, <b>BILINEAR</b>, <b>BICUBIC</b>, or
1242
1400
    #    <b>ANTIALIAS</b> (best quality).  If omitted, it defaults
1243
 
    #    to <b>NEAREST</b> (this will be changed to ANTIALIAS in
1244
 
    #    future versions).
 
1401
    #    to <b>NEAREST</b> (this will be changed to ANTIALIAS in a
 
1402
    #    future version).
1245
1403
    # @return None
1246
1404
 
1247
1405
    def thumbnail(self, size, resample=NEAREST):
1252
1410
 
1253
1411
        # preserve aspect ratio
1254
1412
        x, y = self.size
1255
 
        if x > size[0]: y = y * size[0] / x; x = size[0]
1256
 
        if y > size[1]: x = x * size[1] / y; y = size[1]
 
1413
        if x > size[0]: y = max(y * size[0] / x, 1); x = size[0]
 
1414
        if y > size[1]: x = max(x * size[1] / y, 1); y = size[1]
1257
1415
        size = x, y
1258
1416
 
1259
1417
        if size == self.size:
1280
1438
    # instead of bloating the method docs, add a separate chapter.
1281
1439
 
1282
1440
    ##
1283
 
    # Transform image.  This method creates a new image with the
1284
 
    # given size, and the same mode as the original, and copies
1285
 
    # data to the new image using the given transform.
 
1441
    # Transforms this image.  This method creates a new image with the
 
1442
    # given size, and the same mode as the original, and copies data
 
1443
    # to the new image using the given transform.
1286
1444
    # <p>
1287
1445
    # @def transform(size, method, data, resample=NEAREST)
1288
1446
    # @param size The output size.
1289
1447
    # @param method The transformation method.  This is one of
1290
1448
    #   <b>EXTENT</b> (cut out a rectangular subregion), <b>AFFINE</b>
1291
 
    #   (affine transform), <b>QUAD</b> (map a quadrilateral to a
 
1449
    #   (affine transform), <b>PERSPECTIVE</b> (perspective
 
1450
    #   transform), <b>QUAD</b> (map a quadrilateral to a
1292
1451
    #   rectangle), or <b>MESH</b> (map a number of source quadrilaterals
1293
1452
    #   in one operation).
1294
1453
    # @param data Extra data to the transformation method.
1320
1479
 
1321
1480
    def __transformer(self, box, image, method, data,
1322
1481
                      resample=NEAREST, fill=1):
1323
 
        "Transform into current image"
1324
1482
 
1325
1483
        # FIXME: this should be turned into a lazy operation (?)
1326
1484
 
1338
1496
            ys = float(y1 - y0) / h
1339
1497
            method = AFFINE
1340
1498
            data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
 
1499
        elif method == PERSPECTIVE:
 
1500
            # change argument order to match implementation
 
1501
            data = (data[2], data[0], data[1],
 
1502
                    data[5], data[3], data[4],
 
1503
                    data[6], data[7])
1341
1504
        elif method == QUAD:
1342
1505
            # quadrilateral warp.  data specifies the four corners
1343
1506
            # given as NW, SW, SE, and NE.
1363
1526
        self.im.transform2(box, image.im, method, data, resample, fill)
1364
1527
 
1365
1528
    ##
1366
 
    # Returns a flipped or rotated copy of an image.
 
1529
    # Returns a flipped or rotated copy of this image.
1367
1530
    #
1368
1531
    # @param method One of <b>FLIP_LEFT_RIGHT</b>, <b>FLIP_TOP_BOTTOM</b>,
1369
1532
    # <b>ROTATE_90</b>, <b>ROTATE_180</b>, or <b>ROTATE_270</b>.
1384
1547
 
1385
1548
        Image.__init__(self)
1386
1549
 
 
1550
        x0, y0, x1, y1 = box
 
1551
        if x1 < x0:
 
1552
            x1 = x0
 
1553
        if y1 < y0:
 
1554
            y1 = y0
 
1555
 
1387
1556
        self.mode = im.mode
1388
 
        self.size = box[2]-box[0], box[3]-box[1]
 
1557
        self.size = x1-x0, y1-y0
1389
1558
 
1390
 
        self.__crop = box
 
1559
        self.__crop = x0, y0, x1, y1
1391
1560
 
1392
1561
        self.im = im.im
1393
1562
 
1416
1585
# Creates a new image with the given mode and size.
1417
1586
#
1418
1587
# @param mode The mode to use for the new image.
1419
 
# @param size A 2-tuple, containing (width, height)
 
1588
# @param size A 2-tuple, containing (width, height) in pixels.
1420
1589
# @param color What colour to use for the image.  Default is black.
1421
1590
#    If given, this should be a single integer or floating point value
1422
1591
#    for single-band modes, and a tuple for multi-band modes (one value
1448
1617
# <p>
1449
1618
# You can also use any pixel decoder supported by PIL.  For more
1450
1619
# information on available decoders, see the section <a
1451
 
# href="decoder"><i>Writing Your Own File Decoder</i></a>.
 
1620
# href="pil-decoder.htm"><i>Writing Your Own File Decoder</i></a>.
1452
1621
# <p>
1453
1622
# Note that this function decodes pixel data only, not entire images.
1454
 
# If you have an entire image in a string, wrap it in a <b>StringIO</b>
1455
 
# object, and use <b>open</b> to load it.
 
1623
# If you have an entire image in a string, wrap it in a
 
1624
# <b>StringIO</b> object, and use {@link #open} to load it.
1456
1625
#
1457
1626
# @param mode The image mode.
1458
1627
# @param size The image size.
1476
1645
    return im
1477
1646
 
1478
1647
##
1479
 
# Creates an image memory from pixel data in a string or byte buffer.
 
1648
# (New in 1.1.4) Creates an image memory from pixel data in a string
 
1649
# or byte buffer.
1480
1650
# <p>
1481
 
# This function is similar to <b>fromstring</b>, but it data in
1482
 
# the byte buffer, where possible.  Images created by this function
1483
 
# are usually marked as readonly.
 
1651
# This function is similar to {@link #fromstring}, but uses data in
 
1652
# the byte buffer, where possible.  This means that changes to the
 
1653
# original buffer object are reflected in this image).  Not all modes
 
1654
# can share memory; support modes include "L", "RGBX", "RGBA", and
 
1655
# "CMYK".  For other modes, this function behaves like a corresponding
 
1656
# call to the <b>fromstring</b> function.
1484
1657
# <p>
1485
1658
# Note that this function decodes pixel data only, not entire images.
1486
 
# If you have an entire image in a string, wrap it in a <b>StringIO</b>
1487
 
# object, and use <b>open</b> to load it.
 
1659
# If you have an entire image file in a string, wrap it in a
 
1660
# <b>StringIO</b> object, and use {@link #open} to load it.
1488
1661
#
1489
1662
# @param mode The image mode.
1490
1663
# @param size The image size.
1493
1666
# @param decoder_name What decoder to use.
1494
1667
# @param *args Additional parameters for the given decoder.
1495
1668
# @return An Image object.
 
1669
# @since 1.1.4
1496
1670
 
1497
1671
def frombuffer(mode, size, data, decoder_name="raw", *args):
1498
1672
    "Load image from string or buffer"
1519
1693
# <p>
1520
1694
# This is a lazy operation; this function identifies the file, but the
1521
1695
# actual image data is not read from the file until you try to process
1522
 
# the data (or call the <b>load</b> method).
 
1696
# the data (or call the {@link #Image.load} method).
1523
1697
#
1524
1698
# @def open(file, mode="r")
1525
1699
# @param file A filename (string) or a file object.  The file object
1574
1748
# Image processing.
1575
1749
 
1576
1750
##
1577
 
# Creates a new image by interpolating between the given images, using
 
1751
# Creates a new image by interpolating between two input images, using
1578
1752
# a constant alpha.
1579
1753
#
1580
1754
# <pre>
1599
1773
    return im1._new(core.blend(im1.im, im2.im, alpha))
1600
1774
 
1601
1775
##
1602
 
# Creates a new image by interpolating between the given images,
 
1776
# Creates a new image by interpolating between two input images,
1603
1777
# using the mask as alpha.
1604
1778
#
1605
1779
# @param image1 The first image.
1606
1780
# @param image2 The second image.  Must have the same mode and
1607
1781
#    size as the first image.
1608
1782
# @param mask A mask image.  This image can can have mode
1609
 
#    "1", "L", or "RGBA", and most have the same size as the
 
1783
#    "1", "L", or "RGBA", and must have the same size as the
1610
1784
#    other two images.
1611
1785
 
1612
1786
def composite(image1, image2, mask):
1676
1850
    OPEN[id] = factory, accept
1677
1851
 
1678
1852
##
1679
 
# Register an image MIME type.  This function should not be used
 
1853
# Registers an image MIME type.  This function should not be used
1680
1854
# in application code.
1681
1855
#
1682
1856
# @param id An image format identifier.
1686
1860
    MIME[string.upper(id)] = mimetype
1687
1861
 
1688
1862
##
1689
 
# Register an image save function.  This function should not be
 
1863
# Registers an image save function.  This function should not be
1690
1864
# used in application code.
1691
1865
#
1692
1866
# @param id An image format identifier.
1696
1870
    SAVE[string.upper(id)] = driver
1697
1871
 
1698
1872
##
1699
 
# Register an image extension.  This function should not be
 
1873
# Registers an image extension.  This function should not be
1700
1874
# used in application code.
1701
1875
#
1702
1876
# @param id An image format identifier.
1709
1883
# --------------------------------------------------------------------
1710
1884
# Simple display support
1711
1885
 
1712
 
def _showmime(self, title=None, command=None):
 
1886
def _showxv(image, title=None, command=None):
1713
1887
 
1714
1888
    if os.name == "nt":
1715
1889
        format = "BMP"
1716
1890
        if not command:
1717
1891
            command = "start"
1718
 
    elif os.environ.get("OSTYPE") == "darwin":
 
1892
    elif sys.platform == "darwin":
1719
1893
        format = "JPEG"
1720
1894
        if not command:
1721
1895
            command = "open -a /Applications/Preview.app"
1722
1896
    else:
1723
 
        format = "JPEG"
 
1897
        format = None
1724
1898
        if not command:
1725
 
            command = "see"
 
1899
            command = "xv"
 
1900
            if title:
 
1901
                command = command + " -name \"%s\"" % title
1726
1902
 
1727
 
    if self.mode == "I;16":
 
1903
    if image.mode == "I;16":
1728
1904
        # @PIL88 @PIL101
1729
1905
        # "I;16" isn't an 'official' mode, but we still want to
1730
1906
        # provide a simple way to show 16-bit images.
1731
1907
        base = "L"
1732
1908
    else:
1733
 
        base = getmodebase(self.mode)
1734
 
    if base != self.mode and self.mode != "1":
1735
 
        file = self.convert(base)._dump(format=format)
 
1909
        base = getmodebase(image.mode)
 
1910
    if base != image.mode and image.mode != "1":
 
1911
        file = image.convert(base)._dump(format=format)
1736
1912
    else:
1737
 
        file = self._dump(format=format)
 
1913
        file = image._dump(format=format)
1738
1914
 
1739
1915
    if os.name == "nt":
1740
1916
        os.system("%s %s" % (command, file))
1741
1917
        # FIXME: this leaves temporary files around...
1742
 
    elif os.environ.get("OSTYPE") == "darwin":
 
1918
    elif sys.platform == "darwin":
1743
1919
        # on darwin open returns immediately resulting in the temp
1744
1920
        # file removal while app is opening
1745
1921
        os.system("(%s %s; sleep 20; rm -f %s)&" % (command, file, file))