181
182
"CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
182
183
"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
184
# Experimental modes include I;16, I;16B, RGBa, BGR;15,
185
# and BGR;24. Use these modes only if you know exactly
186
# what you're doing...
185
# Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
186
# BGR;24. Use these modes only if you know exactly what you're
190
if sys.byteorder == 'little':
192
byteorder = sys.byteorder
193
except AttributeError:
195
if struct.unpack("h", "\0\1")[0] == 1:
200
if byteorder == 'little':
207
"1": ('|b1', None), # broken
198
208
"L": ('|u1', None),
199
"I": ('%si4' % _ENDIAN, None), # FIXME: is this correct?
200
"I;16": ('%si2' % _ENDIAN, None),
201
"F": ('%sf4' % _ENDIAN, None), # FIXME: is this correct?
209
"I": (_ENDIAN + 'i4', None),
210
"F": (_ENDIAN + 'f4', None),
202
211
"P": ('|u1', None),
203
212
"RGB": ('|u1', 3),
204
213
"RGBX": ('|u1', 4),
222
231
# raw modes that may be memory mapped. NOTE: if you change this, you
223
232
# may have to modify the stride calculation in map.c too!
224
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16B")
233
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
227
236
# Gets the "base" mode for given mode. This function returns "L" for
630
647
# "1"), all non-zero values are set to 255 (white). To use other
631
648
# thresholds, use the {@link #Image.point} method.
633
# @def convert(mode, matrix=None)
650
# @def convert(mode, matrix=None, **options)
634
651
# @param mode The requested mode.
635
652
# @param matrix An optional conversion matrix. If given, this
636
653
# should be 4- or 16-tuple containing floating point values.
654
# @param options Additional options, given as keyword arguments.
655
# @keyparam dither Dithering method, used when converting from
657
# Available methods are NONE or FLOYDSTEINBERG (default).
658
# @keyparam palette Palette to use when converting from mode "RGB"
659
# to "P". Available palettes are WEB or ADAPTIVE.
660
# @keyparam colors Number of colors to use for the ADAPTIVE palette.
637
662
# @return An Image object.
639
664
def convert(self, mode=None, data=None, dither=None,
1199
1228
def putpalette(self, data, rawmode="RGB"):
1200
1229
"Put palette data into an image."
1203
1231
if self.mode not in ("L", "P"):
1204
1232
raise ValueError("illegal image mode")
1205
if not isStringType(data):
1206
data = string.join(map(chr, data), "")
1234
if isinstance(data, ImagePalette.ImagePalette):
1235
palette = ImagePalette.raw(data.rawmode, data.palette)
1237
if not isStringType(data):
1238
data = string.join(map(chr, data), "")
1239
palette = ImagePalette.raw(rawmode, data)
1207
1240
self.mode = "P"
1208
self.palette = ImagePalette.raw(rawmode, data)
1241
self.palette = palette
1209
1242
self.palette.mode = "RGB"
1210
1243
self.load() # install new palette
1563
1599
def transform(self, size, method, data=None, resample=NEAREST, fill=1):
1564
1600
"Transform image"
1566
import ImageTransform
1567
if isinstance(method, ImageTransform.Transform):
1602
if isinstance(method, ImageTransformHandler):
1603
return method.transform(size, self, resample=resample, fill=fill)
1604
if hasattr(method, "getdata"):
1605
# compatibility w. old-style transform objects
1568
1606
method, data = method.getdata()
1569
1607
if data is None:
1570
1608
raise ValueError("missing method data")
1803
1855
im.readonly = 1
1806
return apply(fromstring, (mode, size, data, decoder_name, args))
1858
return fromstring(mode, size, data, decoder_name, args)
1810
# (New in 1.1.6) Create an image memory from an object exporting
1862
# (New in 1.1.6) Creates an image memory from an object exporting
1811
1863
# the array interface (using the buffer protocol).
1813
1865
# If obj is not contiguous, then the tostring method is called
1826
1878
except KeyError:
1828
1880
if mode is None:
1829
typestr = arr['typestr']
1830
if not (typestr[0] == '|' or typestr[0] == _ENDIAN or
1831
typestr[1:] not in ['u1', 'b1', 'i4', 'f4']):
1832
raise TypeError("cannot handle data-type")
1833
typestr = typestr[:2]
1836
elif typestr == 'f4':
1838
elif typestr == 'b1':
1847
raise TypeError("Do not understand data.")
1850
if mode in ['1','L','I','P','F']:
1882
typekey = (1, 1) + shape[2:], arr['typestr']
1883
mode, rawmode = _fromarray_typemap[typekey]
1886
raise TypeError("Cannot handle this data type")
1889
if mode in ["1", "L", "I", "P", "F"]:
1854
1895
if ndim > ndmax:
1855
1896
raise ValueError("Too many dimensions.")
1857
size = shape[:2][::-1]
1898
size = shape[1], shape[0]
1858
1899
if strides is not None:
1859
1900
obj = obj.tostring()
1861
return frombuffer(mode, size, obj, "raw", mode, 0, 1)
1902
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
1904
_fromarray_typemap = {
1905
# (shape, typestr) => mode, rawmode
1906
# first two members of shape are set to one
1907
# ((1, 1), "|b1"): ("1", "1"), # broken
1908
((1, 1), "|u1"): ("L", "L"),
1909
((1, 1), "|i1"): ("I", "I;8"),
1910
((1, 1), "<i2"): ("I", "I;16"),
1911
((1, 1), ">i2"): ("I", "I;16B"),
1912
((1, 1), "<i4"): ("I", "I;32"),
1913
((1, 1), ">i4"): ("I", "I;32B"),
1914
((1, 1), "<f4"): ("F", "F;32F"),
1915
((1, 1), ">f4"): ("F", "F;32BF"),
1916
((1, 1), "<f8"): ("F", "F;64F"),
1917
((1, 1), ">f8"): ("F", "F;64BF"),
1918
((1, 1, 3), "|u1"): ("RGB", "RGB"),
1919
((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
1923
_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
1924
_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")
1864
1927
# Opens and identifies the given image file.
1903
1966
except (SyntaxError, IndexError, TypeError):
1910
factory, accept = OPEN[i]
1911
if not accept or accept(prefix):
1913
return factory(fp, filename)
1914
except (SyntaxError, IndexError, TypeError):
1973
factory, accept = OPEN[i]
1974
if not accept or accept(prefix):
1976
return factory(fp, filename)
1977
except (SyntaxError, IndexError, TypeError):
1917
1980
raise IOError("cannot identify image file")
2055
2118
# --------------------------------------------------------------------
2056
# Simple display support
2058
def _showxv(image, title=None, command=None):
2062
elif sys.platform == "darwin":
2065
command = "open -a /Applications/Preview.app"
2069
for cmd in ["eog", "gqview", "gwenview", "xv"]:
2074
# raise OSError, "no image viewer found"
2075
print "no image viewer found"
2076
if command in ("xv") and title:
2077
command = command + " -name \"%s\"" % title
2079
if image.mode == "I;16":
2081
# "I;16" isn't an 'official' mode, but we still want to
2082
# provide a simple way to show 16-bit images.
2085
base = getmodebase(image.mode)
2086
if base != image.mode and image.mode != "1":
2087
file = image.convert(base)._dump(format=format)
2089
file = image._dump(format=format)
2092
command = "start /wait %s && del /f %s" % (file, file)
2093
elif sys.platform == "darwin":
2094
# on darwin open returns immediately resulting in the temp
2095
# file removal while app is opening
2096
command = "(%s %s; sleep 20; rm -f %s)&" % (command, file, file)
2098
command = "(%s %s; rm -f %s)&" % (command, file, file)
2102
def _isexecutable(cmd):
2103
if os.path.isfile(cmd):
2104
mode = os.stat(cmd)[stat.ST_MODE]
2105
if mode & stat.S_IXUSR or mode & stat.S_IXGRP or mode & stat.S_IXOTH:
2109
def _iscommand(cmd):
2110
"""Return True if cmd is executable or can be found on the executable
2112
if _isexecutable(cmd):
2114
path = os.environ.get("PATH")
2117
for d in path.split(os.pathsep):
2118
exe = os.path.join(d, cmd)
2119
if _isexecutable(exe):
2119
# Simple display support. User code may override this.
2121
def _show(image, **options):
2122
# override me, as necessary
2123
apply(_showxv, (image,), options)
2125
def _showxv(image, title=None, **options):
2127
apply(ImageShow.show, (image, title), options)