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
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.
31
22
# See the README file for information on usage and redistribution.
36
32
class _imaging_not_installed:
37
33
# module placeholder
56
55
except ImportError, v:
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
66
"The _imaging extension was built for another version "
67
"of Python; most PIL functions will be disabled",
70
except (ImportError, NameError, AttributeError):
62
"The _imaging extension was built for another version "
63
"of Python; most PIL functions will be disabled",
73
67
import ImagePalette
74
68
import os, string, sys
80
74
UnicodeStringType = type(unicode(""))
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)
84
82
def isStringType(t):
85
83
return isinstance(t, StringType)
86
# (Internal) Checks if an object is a tuple.
87
88
def isTupleType(t):
88
89
return isinstance(t, TupleType)
92
# (Internal) Checks if an object is an image object.
90
94
def isImageType(t):
91
95
return hasattr(t, "im")
98
# (Internal) Checks if an object is a string, and that it points to a
93
101
def isDirectory(f):
94
102
return isStringType(f) and os.path.isdir(f)
182
190
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16B")
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.
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.
193
201
def getmodebase(mode):
194
202
# corresponding "base" mode (grayscale or colour)
195
207
return _MODEINFO[mode][0]
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.
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.
205
217
def getmodetype(mode):
206
218
# storage type (per band)
207
223
return _MODEINFO[mode][1]
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
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.
234
# @exception KeyError If the input mode was not a standard mode.
222
236
def getmodebands(mode):
223
237
# return list of subcomponents
224
242
return len(_MODEINFO[mode][2])
226
244
# --------------------------------------------------------------------
470
489
"static char %s_bits[] = {\n" % name, data, "};"], "")
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.
494
# This method is similar to the {@link #fromstring} function, but
495
# loads data into this image instead of creating a new image
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"
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
522
545
def verify(self):
523
546
"Verify file contents."
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.
533
556
# The current version supports all possible conversions between
534
557
# "L", "RGB" and "CMYK."
632
655
return self._new(im)
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
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
667
# @param The crop rectangle, as a (left, upper, right, lower)-tuple.
643
668
# @return An Image object.
645
670
def crop(self, box=None):
720
752
return self.im.getbbox()
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
755
# Returns a list of colors used in this image.
757
# @param maxcolors Maximum number of colors. If this number is
758
# exceeded, this method returns None. The default limit is
760
# @return An unsorted list of (count, pixel) values.
762
def getcolors(self, maxcolors=256):
763
"Get colors from image, up to given limit"
766
if self.mode in ("1", "L", "P"):
767
h = self.im.histogram()
771
out.append((h[i], i))
772
if len(out) > maxcolors:
775
return self.im.getcolors(maxcolors)
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.
728
783
# Note that the sequence object returned by this method is an
729
784
# internal PIL data type, which only supports certain sequence
763
818
return self.im.getextrema()
821
# Returns a PyCObject that points to the internal image memory.
823
# @return A PyCObject object.
826
"Get PyCObject pointer to internal image memory"
833
# Returns the image palette as a list.
835
# @return A list of color values [r, g, b, ...], or None if the
836
# image has no palette.
838
def getpalette(self):
839
"Get palette contents."
843
return map(ord, self.im.getpalette())
845
return None # no palette
766
849
# Returns the pixel value at a given position.
768
851
# @param xy The coordinate, given as (x, y).
859
954
# both source image and mask.
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
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.
869
968
def paste(self, im, box=None, mask=None):
870
969
"Paste other image into region"
971
if isImageType(box) and mask is None:
972
# abbreviated paste(im, mask) syntax
973
mask = box; box = None
873
976
# cover all of self
874
977
box = (0, 0) + self.size
919
1028
def point(self, lut, mode=None):
920
1029
"Map image through lookup table"
922
if self.mode in ("I", "I;16", "F"):
923
# floating point; lut must be a valid expression
924
scale, offset = _getscaleoffset(lut)
926
im = self.im.point_transform(scale, offset);
928
# integer image; use lut and mode
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)
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)
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
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")
1046
return self._new(self.im.point(lut, mode))
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".
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.
943
def putalpha(self, im):
1057
def putalpha(self, alpha):
944
1058
"Set alpha layer"
946
if self.mode != "RGBA" or im.mode not in ("1", "L"):
947
raise ValueError("illegal image mode")
955
self.im.putband(im.im, 3)
1065
if self.mode not in ("LA", "RGBA"):
1066
# attempt to promote self to a matching alpha mode
1068
mode = getmodebase(self.mode) + "A"
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
1077
self.mode = self.im.mode
1078
except (KeyError, ValueError):
1079
raise ValueError("illegal image mode")
1081
if self.mode == "LA":
1086
if isImageType(alpha):
1088
if alpha.mode not in ("1", "L"):
1089
raise ValueError("illegal image mode")
1091
if alpha.mode == "1":
1092
alpha = alpha.convert("L")
1096
self.im.fillband(band, alpha)
1097
except (AttributeError, ValueError):
1098
# do things the hard way
1099
alpha = new("L", self.size, alpha)
1103
self.im.putband(alpha.im, band)
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)
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
981
1130
# @def putpalette(data)
982
# @param data A palette sequence.
1131
# @param data A palette sequence (either a list or a string).
984
1133
def putpalette(self, data, rawmode="RGB"):
985
1134
"Put palette data into an image."
1103
1252
# parameter should always be used.
1104
1253
# @param **options Extra parameters to the image writer.
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.
1107
1260
def save(self, fp, format=None, **params):
1108
1261
"Save image to file or stream"
1110
1263
if isStringType(fp):
1113
fp = __builtin__.open(fp, "wb")
1116
1266
if hasattr(fp, "name") and isStringType(fp.name):
1117
1267
filename = fp.name
1122
1274
self.encoderinfo = params
1123
1275
self.encoderconfig = ()
1129
1279
ext = string.lower(os.path.splitext(filename)[1])
1283
format = EXTENSION[ext]
1287
format = EXTENSION[ext]
1289
raise KeyError(ext) # unknown extension
1134
format = EXTENSION[ext]
1136
SAVE[string.upper(format)](self, fp, filename)
1292
save_handler = SAVE[string.upper(format)]
1143
format = EXTENSION[ext]
1145
SAVE[string.upper(format)](self, fp, filename)
1295
save_handler = SAVE[string.upper(format)] # unknown format
1297
if isStringType(fp):
1299
fp = __builtin__.open(fp, "wb")
1305
save_handler(self, fp, filename)
1307
# do what we can to clean up
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.
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.
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
1161
1323
# @see #Image.tell
1163
1325
def seek(self, frame):
1184
1346
def show(self, title=None, command=None):
1185
1347
"Display image (for debug purposes only)"
1189
ImageTk._show(self, title)
1190
# note: caller must enter mainloop!
1192
_showmime(self, title, command)
1349
_showxv(self, title, command)
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,
1200
1358
# @return A tuple containing bands.
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.
1230
1388
# Note that the bilinear and bicubic filters in the current
1231
1389
# version of PIL are not well-suited for thumbnail generation.
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.
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
1401
# to <b>NEAREST</b> (this will be changed to ANTIALIAS in a
1247
1405
def thumbnail(self, size, resample=NEAREST):
1280
1438
# instead of bloating the method docs, add a separate chapter.
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.
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.
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],
1341
1504
elif method == QUAD:
1342
1505
# quadrilateral warp. data specifies the four corners
1343
1506
# given as NW, SW, SE, and NE.
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>.
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.
1457
1626
# @param mode The image mode.
1458
1627
# @param size The image size.
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
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.
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.
1489
1662
# @param mode The image mode.
1490
1663
# @param size The image size.
1599
1773
return im1._new(core.blend(im1.im, im2.im, alpha))
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.
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.
1612
1786
def composite(image1, image2, mask):
1709
1883
# --------------------------------------------------------------------
1710
1884
# Simple display support
1712
def _showmime(self, title=None, command=None):
1886
def _showxv(image, title=None, command=None):
1714
1888
if os.name == "nt":
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"
1724
1898
if not command:
1901
command = command + " -name \"%s\"" % title
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.
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)
1737
file = self._dump(format=format)
1913
file = image._dump(format=format)
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))