This commit is contained in:
Jerome Leclanche 2017-01-17 13:20:47 +00:00 committed by GitHub
commit 8fcacb9bb1
94 changed files with 409 additions and 566 deletions

View File

@ -17,10 +17,8 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function from PIL import Image, FontFile
from .exceptions import InvalidFileType
from PIL import Image
from PIL import FontFile
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -89,14 +87,12 @@ def bdf_char(f):
# Font file plugin for the X11 BDF format. # Font file plugin for the X11 BDF format.
class BdfFontFile(FontFile.FontFile): class BdfFontFile(FontFile.FontFile):
def __init__(self, fp): def __init__(self, fp):
FontFile.FontFile.__init__(self) FontFile.FontFile.__init__(self)
s = fp.readline() s = fp.readline()
if s[:13] != b"STARTFONT 2.1": if s[:13] != b"STARTFONT 2.1":
raise SyntaxError("not a valid BDF file") raise InvalidFileType("not a valid BDF file")
props = {} props = {}
comments = [] comments = []
@ -111,20 +107,6 @@ class BdfFontFile(FontFile.FontFile):
if s.find(b"LogicalFontDescription") < 0: if s.find(b"LogicalFontDescription") < 0:
comments.append(s[i+1:-1].decode('ascii')) comments.append(s[i+1:-1].decode('ascii'))
# font = props["FONT"].split("-")
# font[4] = bdf_slant[font[4].upper()]
# font[11] = bdf_spacing[font[11].upper()]
# ascent = int(props["FONT_ASCENT"])
# descent = int(props["FONT_DESCENT"])
# fontname = ";".join(font[1:])
# print("#", fontname)
# for i in comments:
# print("#", i)
while True: while True:
c = bdf_char(fp) c = bdf_char(fp)
if not c: if not c:

View File

@ -23,9 +23,10 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image, ImageFile, ImagePalette, _binary
import math import math
from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.7" __version__ = "0.7"
@ -199,7 +200,7 @@ class BmpImageFile(ImageFile.ImageFile):
head_data = self.fp.read(14) head_data = self.fp.read(14)
# choke if the file does not have the required magic bytes # choke if the file does not have the required magic bytes
if head_data[0:2] != b"BM": if head_data[0:2] != b"BM":
raise SyntaxError("Not a BMP file") raise InvalidFileType("Not a BMP file")
# read the start position of the BMP image data (u32) # read the start position of the BMP image data (u32)
offset = i32(head_data[10:14]) offset = i32(head_data[10:14])
# load bitmap information (offset=raster info) # load bitmap information (offset=raster info)

View File

@ -10,6 +10,7 @@
# #
from PIL import Image, ImageFile from PIL import Image, ImageFile
from .exceptions import InvalidFileType
_handler = None _handler = None
@ -37,11 +38,10 @@ class BufrStubImageFile(ImageFile.StubImageFile):
format_description = "BUFR" format_description = "BUFR"
def _open(self): def _open(self):
offset = self.fp.tell() offset = self.fp.tell()
if not _accept(self.fp.read(8)): if not _accept(self.fp.read(8)):
raise SyntaxError("Not a BUFR file") raise InvalidFileType("Not a BUFR file")
self.fp.seek(offset) self.fp.seek(offset)

View File

@ -16,9 +16,9 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
from PIL import Image, BmpImagePlugin, _binary from PIL import Image, BmpImagePlugin, _binary
from .exceptions import InvalidFileType
__version__ = "0.1" __version__ = "0.1"
@ -49,7 +49,7 @@ class CurImageFile(BmpImagePlugin.BmpImageFile):
# check magic # check magic
s = self.fp.read(6) s = self.fp.read(6)
if not _accept(s): if not _accept(s):
raise SyntaxError("not a CUR file") raise InvalidFileType("not a CUR file")
# pick the largest cursor in the file # pick the largest cursor in the file
m = b"" m = b""
@ -59,14 +59,6 @@ class CurImageFile(BmpImagePlugin.BmpImageFile):
m = s m = s
elif i8(s[0]) > i8(m[0]) and i8(s[1]) > i8(m[1]): elif i8(s[0]) > i8(m[0]) and i8(s[1]) > i8(m[1]):
m = s m = s
# print("width", i8(s[0]))
# print("height", i8(s[1]))
# print("colors", i8(s[2]))
# print("reserved", i8(s[3]))
# print("hotspot x", i16(s[4:]))
# print("hotspot y", i16(s[6:]))
# print("bytes", i32(s[8:]))
# print("offset", i32(s[12:]))
if not m: if not m:
raise TypeError("No cursors were found") raise TypeError("No cursors were found")

View File

@ -23,6 +23,8 @@
from PIL import Image, _binary from PIL import Image, _binary
from PIL.PcxImagePlugin import PcxImageFile from PIL.PcxImagePlugin import PcxImageFile
from .exceptions import InvalidFileType
__version__ = "0.2" __version__ = "0.2"
@ -44,11 +46,10 @@ class DcxImageFile(PcxImageFile):
format_description = "Intel DCX" format_description = "Intel DCX"
def _open(self): def _open(self):
# Header # Header
s = self.fp.read(4) s = self.fp.read(4)
if i32(s) != MAGIC: if i32(s) != MAGIC:
raise SyntaxError("not a DCX file") raise InvalidFileType("Invalid DCS header")
# Component directory # Component directory
self._offset = [] self._offset = []

View File

@ -20,10 +20,12 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
import re
import io import io
import re
import sys import sys
from PIL import Image, ImageFile, _binary from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.5" __version__ = "0.5"
@ -235,12 +237,12 @@ class EpsImageFile(ImageFile.ImageFile):
while s: while s:
if len(s) > 255: if len(s) > 255:
raise SyntaxError("not an EPS file") raise PILReadError("Size too large: %r" % (len(s)))
try: try:
m = split.match(s) m = split.match(s)
except re.error as v: except re.error as v:
raise SyntaxError("not an EPS file") raise InvalidFileType("not an EPS file")
if m: if m:
k, v = m.group(1, 2) k, v = m.group(1, 2)
@ -273,7 +275,7 @@ class EpsImageFile(ImageFile.ImageFile):
# tools mistakenly put in the Comments section # tools mistakenly put in the Comments section
pass pass
else: else:
raise IOError("bad EPS header") raise PILReadError("bad EPS header")
s = fp.readline().strip('\r\n') s = fp.readline().strip('\r\n')
@ -284,9 +286,8 @@ class EpsImageFile(ImageFile.ImageFile):
# Scan for an "ImageData" descriptor # Scan for an "ImageData" descriptor
while s[:1] == "%": while s[:1] == "%":
if len(s) > 255: if len(s) > 255:
raise SyntaxError("not an EPS file") raise PILReadError("Size too large: %r" % (len(s)))
if s[:11] == "%ImageData:": if s[:11] == "%ImageData:":
# Encoded bitmapped image. # Encoded bitmapped image.
@ -307,7 +308,7 @@ class EpsImageFile(ImageFile.ImageFile):
break break
if not box: if not box:
raise IOError("cannot determine EPS bounding box") raise PILReadError("cannot determine EPS bounding box")
def _find_offset(self, fp): def _find_offset(self, fp):
@ -327,7 +328,7 @@ class EpsImageFile(ImageFile.ImageFile):
offset = i32(s[4:8]) offset = i32(s[4:8])
length = i32(s[8:12]) length = i32(s[8:12])
else: else:
raise SyntaxError("not an EPS file") raise InvalidFileType("not an EPS file")
return (length, offset) return (length, offset)

View File

@ -10,6 +10,8 @@
# #
from PIL import Image, ImageFile from PIL import Image, ImageFile
from .exceptions import InvalidFileType
_handler = None _handler = None
@ -41,7 +43,7 @@ class FITSStubImageFile(ImageFile.StubImageFile):
offset = self.fp.tell() offset = self.fp.tell()
if not _accept(self.fp.read(6)): if not _accept(self.fp.read(6)):
raise SyntaxError("Not a FITS file") raise InvalidFileType("Not a FITS file")
# FIXME: add more sanity checks here; mandatory header items # FIXME: add more sanity checks here; mandatory header items
# include SIMPLE, BITPIX, NAXIS, etc. # include SIMPLE, BITPIX, NAXIS, etc.

View File

@ -17,6 +17,8 @@
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType
__version__ = "0.2" __version__ = "0.2"
@ -50,7 +52,7 @@ class FliImageFile(ImageFile.ImageFile):
if not (magic in [0xAF11, 0xAF12] and if not (magic in [0xAF11, 0xAF12] and
i16(s[14:16]) in [0, 3] and # flags i16(s[14:16]) in [0, 3] and # flags
s[20:22] == b"\x00\x00"): # reserved s[20:22] == b"\x00\x00"): # reserved
raise SyntaxError("not an FLI/FLC file") raise InvalidFileType("not an FLI/FLC file")
# image characteristics # image characteristics
self.mode = "P" self.mode = "P"

View File

@ -14,8 +14,6 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import os import os
from PIL import Image, _binary from PIL import Image, _binary
@ -90,7 +88,6 @@ class FontFile(object):
x = xx x = xx
s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0 s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
self.bitmap.paste(im.crop(src), s) self.bitmap.paste(im.crop(src), s)
# print(chr(i), dst, s)
self.metrics[i] = d, dst, s self.metrics[i] = d, dst, s
def save(self, filename): def save(self, filename):

View File

@ -15,11 +15,10 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
from PIL import Image, ImageFile, _binary
import olefile import olefile
from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.1" __version__ = "0.1"
@ -65,10 +64,10 @@ class FpxImageFile(ImageFile.ImageFile):
try: try:
self.ole = olefile.OleFileIO(self.fp) self.ole = olefile.OleFileIO(self.fp)
except IOError: except IOError:
raise SyntaxError("not an FPX file; invalid OLE file") raise InvalidFileType("not an FPX file; invalid OLE file")
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B": if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
raise SyntaxError("not an FPX file; bad root CLSID") raise InvalidFileType("not an FPX file; bad root CLSID")
self._open_index(1) self._open_index(1)
@ -116,8 +115,6 @@ class FpxImageFile(ImageFile.ImageFile):
if id in prop: if id in prop:
self.jpeg[i] = prop[id] self.jpeg[i] = prop[id]
# print(len(self.jpeg), "tables loaded")
self._open_subimage(1, self.maxid) self._open_subimage(1, self.maxid)
def _open_subimage(self, index=1, subimage=0): def _open_subimage(self, index=1, subimage=0):
@ -145,10 +142,8 @@ class FpxImageFile(ImageFile.ImageFile):
offset = i32(s, 28) offset = i32(s, 28)
length = i32(s, 32) length = i32(s, 32)
# print(size, self.mode, self.rawmode)
if size != self.size: if size != self.size:
raise IOError("subimage mismatch") raise PILReadError("subimage mismatch")
# get tile descriptors # get tile descriptors
fp.seek(28 + offset) fp.seek(28 + offset)
@ -203,7 +198,7 @@ class FpxImageFile(ImageFile.ImageFile):
self.tile_prefix = self.jpeg[jpeg_tables] self.tile_prefix = self.jpeg[jpeg_tables]
else: else:
raise IOError("unknown/invalid compression") raise PILReadError("unknown/invalid compression")
x = x + xtile x = x + xtile
if x >= xsize: if x >= xsize:

View File

@ -25,6 +25,8 @@
# the color depth field. This is currently unsupported by Pillow. # the color depth field. This is currently unsupported by Pillow.
from PIL import Image, ImageFile, _binary from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType
i32 = _binary.i32be i32 = _binary.i32be
@ -42,20 +44,24 @@ class GbrImageFile(ImageFile.ImageFile):
format_description = "GIMP brush file" format_description = "GIMP brush file"
def _open(self): def _open(self):
header_size = i32(self.fp.read(4)) s = self.fp.read(4)
version = i32(self.fp.read(4)) t = self.fp.read(4)
if len(s) < 4 or len(t) < 4:
raise InvalidFileType("not a GIMP brush")
header_size = i32(s)
version = i32(t)
if header_size < 20: if header_size < 20:
raise SyntaxError("not a GIMP brush") raise InvalidFileType("not a GIMP brush")
if version not in (1, 2): if version not in (1, 2):
raise SyntaxError("Unsupported GIMP brush version: %s" % version) raise NotImplementedError("Unsupported GIMP brush version: %s" % version)
width = i32(self.fp.read(4)) width = i32(self.fp.read(4))
height = i32(self.fp.read(4)) height = i32(self.fp.read(4))
color_depth = i32(self.fp.read(4)) color_depth = i32(self.fp.read(4))
if width <= 0 or height <= 0: if width <= 0 or height <= 0:
raise SyntaxError("not a GIMP brush") raise InvalidFileType("not a GIMP brush")
if color_depth not in (1, 4): if color_depth not in (1, 4):
raise SyntaxError("Unsupported GIMP brush color depth: %s" % color_depth) raise NotImplementedError("Unsupported GIMP brush color depth: %s" % color_depth)
if version == 1: if version == 1:
comment_length = header_size-20 comment_length = header_size-20
@ -63,7 +69,7 @@ class GbrImageFile(ImageFile.ImageFile):
comment_length = header_size-28 comment_length = header_size-28
magic_number = self.fp.read(4) magic_number = self.fp.read(4)
if magic_number != b'GIMP': if magic_number != b'GIMP':
raise SyntaxError("not a GIMP brush, bad magic number") raise InvalidFileType("not a GIMP brush, bad magic number")
self.info['spacing'] = i32(self.fp.read(4)) self.info['spacing'] = i32(self.fp.read(4))
comment = self.fp.read(comment_length)[:-1] comment = self.fp.read(comment_length)[:-1]

View File

@ -25,6 +25,8 @@
from PIL import ImageFile, ImagePalette, _binary from PIL import ImageFile, ImagePalette, _binary
from PIL._util import isPath from PIL._util import isPath
from .exceptions import PILReadError
__version__ = "0.1" __version__ = "0.1"
@ -49,7 +51,6 @@ class GdImageFile(ImageFile.ImageFile):
format_description = "GD uncompressed images" format_description = "GD uncompressed images"
def _open(self): def _open(self):
# Header # Header
s = self.fp.read(775) s = self.fp.read(775)
@ -87,5 +88,5 @@ def open(fp, mode="r"):
try: try:
return GdImageFile(fp, filename) return GdImageFile(fp, filename)
except SyntaxError: except Exception as e:
raise IOError("cannot identify this image file") raise PILReadError("cannot identify this image file: %s" % (e))

View File

@ -26,6 +26,8 @@
from PIL import Image, ImageFile, ImagePalette, \ from PIL import Image, ImageFile, ImagePalette, \
ImageChops, ImageSequence, _binary ImageChops, ImageSequence, _binary
from .exceptions import InvalidFileType
__version__ = "0.9" __version__ = "0.9"
@ -63,11 +65,10 @@ class GifImageFile(ImageFile.ImageFile):
return None return None
def _open(self): def _open(self):
# Screen # Screen
s = self.fp.read(13) s = self.fp.read(13)
if s[:6] not in [b"GIF87a", b"GIF89a"]: if s[:6] not in [b"GIF87a", b"GIF89a"]:
raise SyntaxError("not a GIF file") raise InvalidFileType("Invalid GIF header")
self.info["version"] = s[:6] self.info["version"] = s[:6]
self.size = i16(s[6:]), i16(s[8:]) self.size = i16(s[6:]), i16(s[8:])

View File

@ -15,6 +15,8 @@
from math import pi, log, sin, sqrt from math import pi, log, sin, sqrt
from PIL._binary import o8 from PIL._binary import o8
from .exceptions import InvalidFileType
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# Stuff to translate curve segments to palette values (derived from # Stuff to translate curve segments to palette values (derived from
@ -102,9 +104,8 @@ class GradientFile(object):
class GimpGradientFile(GradientFile): class GimpGradientFile(GradientFile):
def __init__(self, fp): def __init__(self, fp):
if fp.readline()[:13] != b"GIMP Gradient": if fp.readline()[:13] != b"GIMP Gradient":
raise SyntaxError("not a GIMP gradient file") raise InvalidFileType("not a GIMP gradient file")
line = fp.readline() line = fp.readline()

View File

@ -16,21 +16,20 @@
import re import re
from PIL._binary import o8 from PIL._binary import o8
from .exceptions import InvalidFileType, PILReadError
## ##
# File handler for GIMP's palette format. # File handler for GIMP's palette format.
class GimpPaletteFile(object): class GimpPaletteFile(object):
rawmode = "RGB" rawmode = "RGB"
def __init__(self, fp): def __init__(self, fp):
self.palette = [o8(i)*3 for i in range(256)] self.palette = [o8(i)*3 for i in range(256)]
if fp.readline()[:12] != b"GIMP Palette": if fp.readline()[:12] != b"GIMP Palette":
raise SyntaxError("not a GIMP palette file") raise InvalidFileType("not a GIMP palette file")
i = 0 i = 0
@ -44,11 +43,11 @@ class GimpPaletteFile(object):
if re.match(br"\w+:|#", s): if re.match(br"\w+:|#", s):
continue continue
if len(s) > 100: if len(s) > 100:
raise SyntaxError("bad palette file") raise PILReadError("bad palette file")
v = tuple(map(int, s.split()[:3])) v = tuple(map(int, s.split()[:3]))
if len(v) != 3: if len(v) != 3:
raise ValueError("bad palette entry") raise PILReadError("bad palette entry")
if 0 <= i <= 255: if 0 <= i <= 255:
self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2]) self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
@ -58,5 +57,4 @@ class GimpPaletteFile(object):
self.palette = b"".join(self.palette) self.palette = b"".join(self.palette)
def getpalette(self): def getpalette(self):
return self.palette, self.rawmode return self.palette, self.rawmode

View File

@ -10,6 +10,8 @@
# #
from PIL import Image, ImageFile from PIL import Image, ImageFile
from .exceptions import InvalidFileType
_handler = None _handler = None
@ -37,11 +39,10 @@ class GribStubImageFile(ImageFile.StubImageFile):
format_description = "GRIB" format_description = "GRIB"
def _open(self): def _open(self):
offset = self.fp.tell() offset = self.fp.tell()
if not _accept(self.fp.read(8)): if not _accept(self.fp.read(8)):
raise SyntaxError("Not a GRIB file") raise InvalidFileType("Not a GRIB file")
self.fp.seek(offset) self.fp.seek(offset)

View File

@ -10,6 +10,8 @@
# #
from PIL import Image, ImageFile from PIL import Image, ImageFile
from .exceptions import InvalidFileType
_handler = None _handler = None
@ -41,7 +43,7 @@ class HDF5StubImageFile(ImageFile.StubImageFile):
offset = self.fp.tell() offset = self.fp.tell()
if not _accept(self.fp.read(8)): if not _accept(self.fp.read(8)):
raise SyntaxError("Not an HDF file") raise InvalidFileType("Not an HDF file")
self.fp.seek(offset) self.fp.seek(offset)

View File

@ -15,13 +15,15 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image, ImageFile, PngImagePlugin, _binary
import io import io
import os import os
import shutil import shutil
import struct import struct
import sys import sys
import tempfile import tempfile
from PIL import Image, ImageFile, PngImagePlugin, _binary
from .exceptions import InvalidFileType, PILReadError
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version') enable_jpeg2k = hasattr(Image.core, 'jp2klib_version')
if enable_jpeg2k: if enable_jpeg2k:
@ -42,7 +44,7 @@ def read_32t(fobj, start_length, size):
fobj.seek(start) fobj.seek(start)
sig = fobj.read(4) sig = fobj.read(4)
if sig != b'\x00\x00\x00\x00': if sig != b'\x00\x00\x00\x00':
raise SyntaxError('Unknown signature, expecting 0x00000000') raise PILReadError("Unknown signature, expecting 0x00000000")
return read_32(fobj, (start + 4, length - 4), size) return read_32(fobj, (start + 4, length - 4), size)
@ -64,8 +66,8 @@ def read_32(fobj, start_length, size):
im = Image.new("RGB", pixel_size, None) im = Image.new("RGB", pixel_size, None)
for band_ix in range(3): for band_ix in range(3):
data = [] data = []
bytesleft = sizesq rem = sizesq
while bytesleft > 0: while rem > 0:
byte = fobj.read(1) byte = fobj.read(1)
if not byte: if not byte:
break break
@ -78,13 +80,11 @@ def read_32(fobj, start_length, size):
else: else:
blocksize = byte + 1 blocksize = byte + 1
data.append(fobj.read(blocksize)) data.append(fobj.read(blocksize))
bytesleft -= blocksize rem -= blocksize
if bytesleft <= 0: if rem <= 0:
break break
if bytesleft != 0: if rem != 0:
raise SyntaxError( raise PILReadError("Error reading channel (%r bytes left)" % rem)
"Error reading channel [%r left]" % bytesleft
)
band = Image.frombuffer( band = Image.frombuffer(
"L", pixel_size, b"".join(data), "raw", "L", 0, 1 "L", pixel_size, b"".join(data), "raw", "L", 0, 1
) )
@ -187,12 +187,12 @@ class IcnsFile(object):
self.fobj = fobj self.fobj = fobj
sig, filesize = nextheader(fobj) sig, filesize = nextheader(fobj)
if sig != b'icns': if sig != b'icns':
raise SyntaxError('not an icns file') raise InvalidFileType("not an icns file")
i = HEADERSIZE i = HEADERSIZE
while i < filesize: while i < filesize:
sig, blocksize = nextheader(fobj) sig, blocksize = nextheader(fobj)
if blocksize <= 0: if blocksize <= 0:
raise SyntaxError('invalid block header') raise PILReadError("invalid block header")
i += HEADERSIZE i += HEADERSIZE
blocksize -= HEADERSIZE blocksize -= HEADERSIZE
dct[sig] = (i, blocksize) dct[sig] = (i, blocksize)
@ -211,7 +211,7 @@ class IcnsFile(object):
def bestsize(self): def bestsize(self):
sizes = self.itersizes() sizes = self.itersizes()
if not sizes: if not sizes:
raise SyntaxError("No 32bit icon resources found") raise PILReadError("No 32bit icon resources found")
return max(sizes) return max(sizes)
def dataforsize(self, size): def dataforsize(self, size):

View File

@ -21,12 +21,11 @@
# * https://en.wikipedia.org/wiki/ICO_(file_format) # * https://en.wikipedia.org/wiki/ICO_(file_format)
# * https://msdn.microsoft.com/en-us/library/ms997538.aspx # * https://msdn.microsoft.com/en-us/library/ms997538.aspx
import struct import struct
from io import BytesIO from io import BytesIO
from PIL import Image, ImageFile, BmpImagePlugin, PngImagePlugin, _binary
from math import log, ceil from math import log, ceil
from PIL import Image, ImageFile, BmpImagePlugin, PngImagePlugin, _binary
from .exceptions import InvalidFileType
__version__ = "0.1" __version__ = "0.1"
@ -91,7 +90,7 @@ class IcoFile(object):
# check magic # check magic
s = buf.read(6) s = buf.read(6)
if not _accept(s): if not _accept(s):
raise SyntaxError("not an ICO file") raise InvalidFileType("not an ICO file")
self.buf = buf self.buf = buf
self.entry = [] self.entry = []

View File

@ -29,6 +29,8 @@
import re import re
from PIL import Image, ImageFile, ImagePalette from PIL import Image, ImageFile, ImagePalette
from PIL._binary import i8 from PIL._binary import i8
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.7" __version__ = "0.7"
@ -111,12 +113,11 @@ class ImImageFile(ImageFile.ImageFile):
format_description = "IFUNC Image Memory" format_description = "IFUNC Image Memory"
def _open(self): def _open(self):
# Quick rejection: if there's not an LF among the first # Quick rejection: if there's not an LF among the first
# 100 bytes, this is (probably) not a text header. # 100 bytes, this is (probably) not a text header.
if b"\n" not in self.fp.read(100): if b"\n" not in self.fp.read(100):
raise SyntaxError("not an IM file") raise InvalidFileType("not an IM file")
self.fp.seek(0) self.fp.seek(0)
n = 0 n = 0
@ -129,7 +130,6 @@ class ImImageFile(ImageFile.ImageFile):
self.rawmode = "L" self.rawmode = "L"
while True: while True:
s = self.fp.read(1) s = self.fp.read(1)
# Some versions of IFUNC uses \n\r instead of \r\n... # Some versions of IFUNC uses \n\r instead of \r\n...
@ -143,7 +143,7 @@ class ImImageFile(ImageFile.ImageFile):
s = s + self.fp.readline() s = s + self.fp.readline()
if len(s) > 100: if len(s) > 100:
raise SyntaxError("not an IM file") raise InvalidFileType("not an IM file")
if s[-2:] == b'\r\n': if s[-2:] == b'\r\n':
s = s[:-2] s = s[:-2]
@ -153,10 +153,9 @@ class ImImageFile(ImageFile.ImageFile):
try: try:
m = split.match(s) m = split.match(s)
except re.error as v: except re.error as v:
raise SyntaxError("not an IM file") raise InvalidFileType("not an IM file")
if m: if m:
k, v = m.group(1, 2) k, v = m.group(1, 2)
# Don't know if this is the correct encoding, # Don't know if this is the correct encoding,
@ -187,12 +186,11 @@ class ImImageFile(ImageFile.ImageFile):
n += 1 n += 1
else: else:
s = s.decode("ascii", "replace")
raise SyntaxError("Syntax error in IM header: " + raise PILReadError("Bad IM header: %r" % (s))
s.decode('ascii', 'replace'))
if not n: if not n:
raise SyntaxError("Not an IM file") raise InvalidFileType("Not an IM file")
# Basic attributes # Basic attributes
self.size = self.info[SIZE] self.size = self.info[SIZE]
@ -202,7 +200,7 @@ class ImImageFile(ImageFile.ImageFile):
while s and s[0:1] != b'\x1A': while s and s[0:1] != b'\x1A':
s = self.fp.read(1) s = self.fp.read(1)
if not s: if not s:
raise SyntaxError("File truncated") raise PILReadError("File truncated")
if LUT in self.info: if LUT in self.info:
# convert lookup table to palette or lut attribute # convert lookup table to palette or lut attribute

View File

@ -24,13 +24,11 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
from PIL import VERSION, PILLOW_VERSION, _plugins
import logging import logging
import warnings
import math import math
import warnings
from PIL import VERSION, PILLOW_VERSION, _plugins
from .exceptions import PILReadError, NoPluginFound
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -418,7 +416,6 @@ def _getdecoder(mode, decoder_name, args, extra=()):
try: try:
# get decoder # get decoder
decoder = getattr(core, decoder_name + "_decoder") decoder = getattr(core, decoder_name + "_decoder")
# print(decoder, mode, args + extra)
return decoder(mode, *args + extra) return decoder(mode, *args + extra)
except AttributeError: except AttributeError:
raise IOError("decoder %s not available" % decoder_name) raise IOError("decoder %s not available" % decoder_name)
@ -435,7 +432,6 @@ def _getencoder(mode, encoder_name, args, extra=()):
try: try:
# get encoder # get encoder
encoder = getattr(core, encoder_name + "_encoder") encoder = getattr(core, encoder_name + "_encoder")
# print(encoder, mode, args + extra)
return encoder(mode, *args + extra) return encoder(mode, *args + extra)
except AttributeError: except AttributeError:
raise IOError("encoder %s not available" % encoder_name) raise IOError("encoder %s not available" % encoder_name)
@ -1583,7 +1579,7 @@ class Image(object):
angle = angle % 360.0 angle = angle % 360.0
# Fast paths regardless of filter, as long as we're not # Fast paths regardless of filter, as long as we're not
# translating or changing the center. # translating or changing the center.
if not (center or translate): if not (center or translate):
if angle == 0: if angle == 0:
return self.copy() return self.copy()
@ -2194,7 +2190,6 @@ def fromarray(obj, mode=None):
typekey = (1, 1) + shape[2:], arr['typestr'] typekey = (1, 1) + shape[2:], arr['typestr']
mode, rawmode = _fromarray_typemap[typekey] mode, rawmode = _fromarray_typemap[typekey]
except KeyError: except KeyError:
# print(typekey)
raise TypeError("Cannot handle this data type") raise TypeError("Cannot handle this data type")
else: else:
rawmode = mode rawmode = mode
@ -2329,7 +2324,7 @@ def open(fp, mode="r"):
im = factory(fp, filename) im = factory(fp, filename)
_decompression_bomb_check(im.size) _decompression_bomb_check(im.size)
return im return im
except (SyntaxError, IndexError, TypeError, struct.error): except (PILReadError, NoPluginFound, IndexError, TypeError, struct.error):
# Leave disabled by default, spams the logs with image # Leave disabled by default, spams the logs with image
# opening failures that are entirely expected. # opening failures that are entirely expected.
# logger.debug("", exc_info=True) # logger.debug("", exc_info=True)

View File

@ -15,7 +15,6 @@
# See the README file for information on usage and redistribution. See # See the README file for information on usage and redistribution. See
# below for the original description. # below for the original description.
from __future__ import print_function
import sys import sys
from PIL import Image from PIL import Image
@ -28,6 +27,7 @@ except ImportError as ex:
_imagingcms = deferred_error(ex) _imagingcms = deferred_error(ex)
from PIL._util import isStringType from PIL._util import isStringType
DESCRIPTION = """ DESCRIPTION = """
pyCMS pyCMS
@ -149,7 +149,6 @@ for flag in FLAGS.values():
# Profile. # Profile.
class ImageCmsProfile(object): class ImageCmsProfile(object):
def __init__(self, profile): def __init__(self, profile):
""" """
:param profile: Either a string representing a filename, :param profile: Either a string representing a filename,
@ -166,7 +165,6 @@ class ImageCmsProfile(object):
self._set(profile) self._set(profile)
else: else:
raise TypeError("Invalid type for Profile") raise TypeError("Invalid type for Profile")
def _set(self, profile, filename=None): def _set(self, profile, filename=None):
self.profile = profile self.profile = profile

View File

@ -27,12 +27,14 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image
from PIL._util import isPath
import io import io
import os import os
import sys import sys
import struct import struct
from PIL import Image
from PIL._util import isPath
from .exceptions import PILReadError, NoPluginFound
MAXBLOCK = 65536 MAXBLOCK = 65536
@ -100,10 +102,10 @@ class ImageFile(Image.Image):
KeyError, # unsupported mode KeyError, # unsupported mode
EOFError, # got header but not the first frame EOFError, # got header but not the first frame
struct.error) as v: struct.error) as v:
raise SyntaxError(v) raise PILReadError(v)
if not self.mode or self.size[0] <= 0: if not self.mode or self.size[0] <= 0:
raise SyntaxError("not identified by this driver") raise NoPluginFound("not identified by this driver")
def draft(self, mode, size): def draft(self, mode, size):
"Set draft mode" "Set draft mode"

View File

@ -25,10 +25,11 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image
from PIL._util import isDirectory, isPath
import os import os
import sys import sys
from PIL import Image
from PIL._util import isDirectory, isPath
from .exceptions import InvalidFileType
class _imagingft_not_installed(object): class _imagingft_not_installed(object):
@ -61,7 +62,6 @@ class ImageFont(object):
"PIL font wrapper" "PIL font wrapper"
def _load_pilfont(self, filename): def _load_pilfont(self, filename):
with open(filename, "rb") as fp: with open(filename, "rb") as fp:
for ext in (".png", ".gif", ".pbm"): for ext in (".png", ".gif", ".pbm"):
try: try:
@ -80,10 +80,9 @@ class ImageFont(object):
return self._load_pilfont_data(fp, image) return self._load_pilfont_data(fp, image)
def _load_pilfont_data(self, file, image): def _load_pilfont_data(self, file, image):
# read PILfont header # read PILfont header
if file.readline() != b"PILfont\n": if file.readline() != b"PILfont\n":
raise SyntaxError("Not a PILfont file") raise InvalidFileType("Not a PILfont file")
file.readline().split(b";") file.readline().split(b";")
self.info = [] # FIXME: should be a dictionary self.info = [] # FIXME: should be a dictionary
while True: while True:

View File

@ -5,11 +5,10 @@
# #
# Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com> # Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
from __future__ import print_function import re
from PIL import Image from PIL import Image
from PIL import _imagingmorph from PIL import _imagingmorph
import re
LUT_SIZE = 1 << 9 LUT_SIZE = 1 << 9
@ -152,11 +151,6 @@ class LutBuilder(object):
patterns += self._pattern_permute(pattern, options, result) patterns += self._pattern_permute(pattern, options, result)
# # Debugging
# for p,r in patterns:
# print(p,r)
# print('--')
# compile the patterns into regular expressions for speed # compile the patterns into regular expressions for speed
for i, pattern in enumerate(patterns): for i, pattern in enumerate(patterns):
p = pattern[0].replace('.', 'X').replace('X', '[01]') p = pattern[0].replace('.', 'X').replace('X', '[01]')

View File

@ -17,10 +17,8 @@
# #
import array import array
from PIL import ImageColor from PIL import GimpPaletteFile, GimpGradientFile, ImageColor, PaletteFile
from PIL import GimpPaletteFile from .exceptions import PILReadError
from PIL import GimpGradientFile
from PIL import PaletteFile
class ImagePalette(object): class ImagePalette(object):
@ -198,7 +196,6 @@ def load(filename):
# FIXME: supports GIMP gradients only # FIXME: supports GIMP gradients only
with open(filename, "rb") as fp: with open(filename, "rb") as fp:
for paletteHandler in [ for paletteHandler in [
GimpPaletteFile.GimpPaletteFile, GimpPaletteFile.GimpPaletteFile,
GimpGradientFile.GimpGradientFile, GimpGradientFile.GimpGradientFile,
@ -209,11 +206,9 @@ def load(filename):
lut = paletteHandler(fp).getpalette() lut = paletteHandler(fp).getpalette()
if lut: if lut:
break break
except (SyntaxError, ValueError): except (PILReadError, ValueError):
# import traceback
# traceback.print_exc()
pass pass
else: else:
raise IOError("cannot load palette") raise IOError("cannot load palette")
return lut # data, rawmode return lut

View File

@ -12,8 +12,6 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
from PIL import Image from PIL import Image
import os import os
import sys import sys

View File

@ -14,10 +14,10 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
import re import re
from PIL import Image, ImageFile from PIL import Image, ImageFile
from .exceptions import InvalidFileType
__version__ = "0.2" __version__ = "0.2"
@ -37,12 +37,11 @@ class ImtImageFile(ImageFile.ImageFile):
format_description = "IM Tools" format_description = "IM Tools"
def _open(self): def _open(self):
# Quick rejection: if there's not a LF among the first # Quick rejection: if there's not a LF among the first
# 100 bytes, this is (probably) not a text header. # 100 bytes, this is (probably) not a text header.
if b"\n" not in self.fp.read(100): if b"\n" not in self.fp.read(100):
raise SyntaxError("not an IM file") raise InvalidFileType("not an IM file")
self.fp.seek(0) self.fp.seek(0)
xsize = ysize = 0 xsize = ysize = 0

View File

@ -15,11 +15,11 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
from PIL import Image, ImageFile, _binary
import os import os
import tempfile import tempfile
from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType
__version__ = "0.3" __version__ = "0.3"
@ -43,12 +43,6 @@ def i(c):
return i32((PAD + c)[-4:]) return i32((PAD + c)[-4:])
def dump(c):
for i in c:
print("%02x" % i8(i), end=' ')
print()
## ##
# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields # Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
# from TIFF and JPEG files, use the <b>getiptcinfo</b> function. # from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
@ -72,7 +66,7 @@ class IptcImageFile(ImageFile.ImageFile):
# syntax # syntax
if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9: if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9:
raise SyntaxError("invalid IPTC/NAA file") raise InvalidFileType("invalid IPTC/NAA file")
# field size # field size
size = i8(s[3]) size = i8(s[3])
@ -107,8 +101,6 @@ class IptcImageFile(ImageFile.ImageFile):
else: else:
self.info[tag] = tagdata self.info[tag] = tagdata
# print(tag, self.info[tag])
# mode # mode
layers = i8(self.info[(3, 60)][0]) layers = i8(self.info[(3, 60)][0])
component = i8(self.info[(3, 60)][1]) component = i8(self.info[(3, 60)][1])

View File

@ -12,10 +12,12 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image, ImageFile
import struct
import os
import io import io
import os
import struct
from PIL import Image, ImageFile
from .exceptions import PILReadError, InvalidFileType
__version__ = "0.1" __version__ = "0.1"
@ -70,7 +72,7 @@ def _parse_jp2_header(fp):
hlen = 8 hlen = 8
if lbox < hlen: if lbox < hlen:
raise SyntaxError('Invalid JP2 header length') raise PILReadError("Invalid JP2 header length")
if tbox == b'jp2h': if tbox == b'jp2h':
header = fp.read(lbox - hlen) header = fp.read(lbox - hlen)
@ -79,7 +81,7 @@ def _parse_jp2_header(fp):
fp.seek(lbox - hlen, os.SEEK_CUR) fp.seek(lbox - hlen, os.SEEK_CUR)
if header is None: if header is None:
raise SyntaxError('could not find JP2 header') raise PILReadError("Could not find JP2 header")
size = None size = None
mode = None mode = None
@ -143,7 +145,7 @@ def _parse_jp2_header(fp):
break break
if size is None or mode is None: if size is None or mode is None:
raise SyntaxError("Malformed jp2 header") raise PILReadError("Malformed jp2 header")
return (size, mode) return (size, mode)
@ -167,10 +169,10 @@ class Jpeg2KImageFile(ImageFile.ImageFile):
self.codec = "jp2" self.codec = "jp2"
self.size, self.mode = _parse_jp2_header(self.fp) self.size, self.mode = _parse_jp2_header(self.fp)
else: else:
raise SyntaxError('not a JPEG 2000 file') raise InvalidFileType("not a JPEG 2000 file")
if self.size is None or self.mode is None: if self.size is None or self.mode is None:
raise SyntaxError('unable to determine size/mode') raise PILReadError("unable to determine size/mode")
self.reduce = 0 self.reduce = 0
self.layers = 0 self.layers = 0

View File

@ -32,16 +32,16 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import array import array
import struct import struct
import io import io
import warnings import warnings
from PIL import Image, ImageFile, TiffImagePlugin, _binary from PIL import Image, ImageFile, TiffImagePlugin, _binary
from .exceptions import InvalidFileType, PILReadError
from PIL.JpegPresets import presets from PIL.JpegPresets import presets
from PIL._util import isStringType from PIL._util import isStringType
i8 = _binary.i8 i8 = _binary.i8
o8 = _binary.o8 o8 = _binary.o8
i16 = _binary.i16be i16 = _binary.i16be
@ -146,7 +146,7 @@ def SOF(self, marker):
self.bits = i8(s[0]) self.bits = i8(s[0])
if self.bits != 8: if self.bits != 8:
raise SyntaxError("cannot handle %d-bit layers" % self.bits) raise NotImplementedError("cannot handle %d-bit layers" % self.bits)
self.layers = i8(s[5]) self.layers = i8(s[5])
if self.layers == 1: if self.layers == 1:
@ -156,7 +156,7 @@ def SOF(self, marker):
elif self.layers == 4: elif self.layers == 4:
self.mode = "CMYK" self.mode = "CMYK"
else: else:
raise SyntaxError("cannot handle %d-layer images" % self.layers) raise NotImplementedError("cannot handle %d-layer images" % self.layers)
if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]: if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
self.info["progressive"] = self.info["progression"] = 1 self.info["progressive"] = self.info["progression"] = 1
@ -193,14 +193,13 @@ def DQT(self, marker):
s = ImageFile._safe_read(self.fp, n) s = ImageFile._safe_read(self.fp, n)
while len(s): while len(s):
if len(s) < 65: if len(s) < 65:
raise SyntaxError("bad quantization table marker") raise PILReadError("bad quantization table marker")
v = i8(s[0]) v = i8(s[0])
if v//16 == 0: if v//16 == 0:
self.quantization[v & 15] = array.array("B", s[1:65]) self.quantization[v & 15] = array.array("B", s[1:65])
s = s[65:] s = s[65:]
else: else:
return # FIXME: add code to read 16-bit tables! return # FIXME: add code to read 16-bit tables!
# raise SyntaxError, "bad quantization table element size"
# #
@ -290,7 +289,7 @@ class JpegImageFile(ImageFile.ImageFile):
s = self.fp.read(1) s = self.fp.read(1)
if i8(s) != 255: if i8(s) != 255:
raise SyntaxError("not a JPEG file") raise InvalidFileType("not a JPEG file")
# Create attributes # Create attributes
self.bits = self.layers = 0 self.bits = self.layers = 0
@ -317,7 +316,6 @@ class JpegImageFile(ImageFile.ImageFile):
if i in MARKER: if i in MARKER:
name, description, handler = MARKER[i] name, description, handler = MARKER[i]
# print(hex(i), name, description)
if handler is not None: if handler is not None:
handler(self, i) handler(self, i)
if i == 0xFFDA: # start of scan if i == 0xFFDA: # start of scan
@ -335,7 +333,7 @@ class JpegImageFile(ImageFile.ImageFile):
elif i == 0xFF00: # Skip extraneous data (escaped 0xFF) elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)
s = self.fp.read(1) s = self.fp.read(1)
else: else:
raise SyntaxError("no marker found") raise PILReadError("no marker found")
def draft(self, mode, size): def draft(self, mode, size):
@ -481,12 +479,12 @@ def _getmp(self):
info.load(file_contents) info.load(file_contents)
mp = dict(info) mp = dict(info)
except: except:
raise SyntaxError("malformed MP Index (unreadable directory)") raise PILReadError("malformed MP Index (unreadable directory)")
# it's an error not to have a number of images # it's an error not to have a number of images
try: try:
quant = mp[0xB001] quant = mp[0xB001]
except KeyError: except KeyError:
raise SyntaxError("malformed MP Index (no number of images)") raise PILReadError("malformed MP Index (no number of images)")
# get MP entries # get MP entries
mpentries = [] mpentries = []
try: try:
@ -511,7 +509,7 @@ def _getmp(self):
if mpentryattr['ImageDataFormat'] == 0: if mpentryattr['ImageDataFormat'] == 0:
mpentryattr['ImageDataFormat'] = 'JPEG' mpentryattr['ImageDataFormat'] = 'JPEG'
else: else:
raise SyntaxError("unsupported picture format in MPO") raise PILReadError("unsupported picture format in MPO")
mptypemap = { mptypemap = {
0x000000: 'Undefined', 0x000000: 'Undefined',
0x010001: 'Large Thumbnail (VGA Equivalent)', 0x010001: 'Large Thumbnail (VGA Equivalent)',
@ -527,7 +525,7 @@ def _getmp(self):
mpentries.append(mpentry) mpentries.append(mpentry)
mp[0xB002] = mpentries mp[0xB002] = mpentries
except KeyError: except KeyError:
raise SyntaxError("malformed MP Index (bad MP Entry)") raise PILReadError("malformed MP Index (bad MP Entry)")
# Next we should try and parse the individual image unique ID list; # Next we should try and parse the individual image unique ID list;
# we don't because I've never seen this actually used in a real MPO # we don't because I've never seen this actually used in a real MPO
# file and so can't test it. # file and so can't test it.
@ -758,7 +756,7 @@ def jpeg_factory(fp=None, filename=None):
except (TypeError, IndexError): except (TypeError, IndexError):
# It is really a JPEG # It is really a JPEG
pass pass
except SyntaxError: except PILReadError:
warnings.warn("Image appears to be a malformed MPO file, it will be " warnings.warn("Image appears to be a malformed MPO file, it will be "
"interpreted as a base JPEG file") "interpreted as a base JPEG file")
return im return im

View File

@ -18,6 +18,8 @@
import struct import struct
from PIL import Image, ImageFile from PIL import Image, ImageFile
from .exceptions import InvalidFileType
__version__ = "0.2" __version__ = "0.2"
@ -35,11 +37,10 @@ class McIdasImageFile(ImageFile.ImageFile):
format_description = "McIdas area file" format_description = "McIdas area file"
def _open(self): def _open(self):
# parse area file directory # parse area file directory
s = self.fp.read(256) s = self.fp.read(256)
if not _accept(s) or len(s) != 256: if not _accept(s) or len(s) != 256:
raise SyntaxError("not an McIdas area file") raise InvalidFileType("not an McIdas area file")
self.area_descriptor_raw = s self.area_descriptor_raw = s
self.area_descriptor = w = [0] + list(struct.unpack("!64i", s)) self.area_descriptor = w = [0] + list(struct.unpack("!64i", s))
@ -56,7 +57,7 @@ class McIdasImageFile(ImageFile.ImageFile):
mode = "I" mode = "I"
rawmode = "I;32B" rawmode = "I;32B"
else: else:
raise SyntaxError("unsupported McIdas format") raise NotImplementedError("unsupported McIdas format: %r" % (w[11]))
self.mode = mode self.mode = mode
self.size = w[10], w[9] self.size = w[10], w[9]

View File

@ -16,10 +16,10 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image, TiffImagePlugin
import olefile import olefile
from PIL import Image, TiffImagePlugin
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.1" __version__ = "0.1"
@ -48,7 +48,7 @@ class MicImageFile(TiffImagePlugin.TiffImageFile):
try: try:
self.ole = olefile.OleFileIO(self.fp) self.ole = olefile.OleFileIO(self.fp)
except IOError: except IOError:
raise SyntaxError("not an MIC file; invalid OLE file") raise InvalidFileType("not an MIC file; invalid OLE file")
# find ACI subfiles with Image members (maybe not the # find ACI subfiles with Image members (maybe not the
# best way to identify MIC files, but what the... ;-) # best way to identify MIC files, but what the... ;-)
@ -61,7 +61,7 @@ class MicImageFile(TiffImagePlugin.TiffImageFile):
# if we didn't find any images, this is probably not # if we didn't find any images, this is probably not
# an MIC file. # an MIC file.
if not self.images: if not self.images:
raise SyntaxError("not an MIC file; no image entries") raise PILReadError("not an MIC file; no image entries")
self.__fp = self.fp self.__fp = self.fp
self.frame = 0 self.frame = 0

View File

@ -16,6 +16,8 @@
from PIL import Image, ImageFile from PIL import Image, ImageFile
from PIL._binary import i8 from PIL._binary import i8
from .exceptions import InvalidFileType
__version__ = "0.1" __version__ = "0.1"
@ -65,11 +67,10 @@ class MpegImageFile(ImageFile.ImageFile):
format_description = "MPEG" format_description = "MPEG"
def _open(self): def _open(self):
s = BitStream(self.fp) s = BitStream(self.fp)
if s.read(32) != 0x1B3: if s.read(32) != 0x1B3:
raise SyntaxError("not an MPEG file") raise InvalidFileType("not an MPEG file")
self.mode = "RGB" self.mode = "RGB"
self.size = s.read(12), s.read(12) self.size = s.read(12), s.read(12)

View File

@ -18,6 +18,8 @@
from PIL import Image, ImageFile, _binary from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.1" __version__ = "0.1"
@ -46,14 +48,14 @@ class MspImageFile(ImageFile.ImageFile):
# Header # Header
s = self.fp.read(32) s = self.fp.read(32)
if s[:4] not in [b"DanM", b"LinS"]: if s[:4] not in [b"DanM", b"LinS"]:
raise SyntaxError("not an MSP file") raise InvalidFileType("not an MSP file")
# Header checksum # Header checksum
checksum = 0 checksum = 0
for i in range(0, 32, 2): for i in range(0, 32, 2):
checksum = checksum ^ i16(s[i:i+2]) checksum = checksum ^ i16(s[i:i+2])
if checksum != 0: if checksum != 0:
raise SyntaxError("bad MSP checksum") raise PILReadError("bad MSP checksum")
self.mode = "1" self.mode = "1"
self.size = i16(s[4:]), i16(s[6:]) self.size = i16(s[4:]), i16(s[6:])

View File

@ -14,6 +14,7 @@
# #
from PIL._binary import o8 from PIL._binary import o8
from .exceptions import InvalidFileType
## ##
@ -24,11 +25,9 @@ class PaletteFile(object):
rawmode = "RGB" rawmode = "RGB"
def __init__(self, fp): def __init__(self, fp):
self.palette = [(i, i, i) for i in range(256)] self.palette = [(i, i, i) for i in range(256)]
while True: while True:
s = fp.readline() s = fp.readline()
if not s: if not s:
@ -36,7 +35,7 @@ class PaletteFile(object):
if s[0:1] == b"#": if s[0:1] == b"#":
continue continue
if len(s) > 100: if len(s) > 100:
raise SyntaxError("bad palette file") raise PILReadError("bad palette file")
v = [int(x) for x in s.split()] v = [int(x) for x in s.split()]
try: try:

View File

@ -14,8 +14,9 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image, ImageFile, _binary from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType
__version__ = "0.1" __version__ = "0.1"
@ -39,7 +40,7 @@ class PcdImageFile(ImageFile.ImageFile):
s = self.fp.read(2048) s = self.fp.read(2048)
if s[:4] != b"PCD_": if s[:4] != b"PCD_":
raise SyntaxError("not a PCD file") raise InvalidFileType("not a PCD file")
orientation = i8(s[1538]) & 3 orientation = i8(s[1538]) & 3
self.tile_post_rotate = None self.tile_post_rotate = None

View File

@ -16,9 +16,9 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image from PIL import FontFile, Image, _binary
from PIL import FontFile from .exceptions import InvalidFileType, PILReadError
from PIL import _binary
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# declarations # declarations
@ -64,7 +64,7 @@ class PcfFontFile(FontFile.FontFile):
magic = l32(fp.read(4)) magic = l32(fp.read(4))
if magic != PCF_MAGIC: if magic != PCF_MAGIC:
raise SyntaxError("not a PCF file") raise InvalidFileType("not a PCF file")
FontFile.FontFile.__init__(self) FontFile.FontFile.__init__(self)
@ -194,7 +194,7 @@ class PcfFontFile(FontFile.FontFile):
nbitmaps = i32(fp.read(4)) nbitmaps = i32(fp.read(4))
if nbitmaps != len(metrics): if nbitmaps != len(metrics):
raise IOError("Wrong number of bitmaps") raise PILReadError("Wrong number of bitmaps")
offsets = [] offsets = []
for i in range(nbitmaps): for i in range(nbitmaps):

View File

@ -25,10 +25,10 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import logging import logging
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType, PILReadError
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -52,16 +52,15 @@ class PcxImageFile(ImageFile.ImageFile):
format_description = "Paintbrush" format_description = "Paintbrush"
def _open(self): def _open(self):
# header # header
s = self.fp.read(128) s = self.fp.read(128)
if not _accept(s): if not _accept(s):
raise SyntaxError("not a PCX file") raise InvalidFileType("not a PCX file")
# image # image
bbox = i16(s, 4), i16(s, 6), i16(s, 8)+1, i16(s, 10)+1 bbox = i16(s, 4), i16(s, 6), i16(s, 8)+1, i16(s, 10)+1
if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
raise SyntaxError("bad PCX image size") raise PILReadError("bad PCX image size")
logger.debug("BBox: %s %s %s %s", *bbox) logger.debug("BBox: %s %s %s %s", *bbox)
# format # format

View File

@ -20,6 +20,8 @@
# #
from PIL import Image, ImageFile, _binary from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType
__version__ = "0.1" __version__ = "0.1"
@ -46,7 +48,7 @@ class PixarImageFile(ImageFile.ImageFile):
# assuming a 4-byte magic label # assuming a 4-byte magic label
s = self.fp.read(4) s = self.fp.read(4)
if s != b"\200\350\000\000": if s != b"\200\350\000\000":
raise SyntaxError("not a PIXAR file") raise InvalidFileType("not a PIXAR file")
# read rest of header # read rest of header
s = s + self.fp.read(508) s = s + self.fp.read(508)

View File

@ -31,14 +31,13 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import logging import logging
import re import re
import zlib import zlib
import struct import struct
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.9" __version__ = "0.9"
@ -118,7 +117,7 @@ class ChunkStream(object):
length = i32(s) length = i32(s)
if not is_cid(cid): if not is_cid(cid):
raise SyntaxError("broken PNG file (chunk %s)" % repr(cid)) raise PILReadError("broken PNG file (chunk %s)" % repr(cid))
return cid, pos, length return cid, pos, length
@ -148,11 +147,9 @@ class ChunkStream(object):
crc1 = Image.core.crc32(data, Image.core.crc32(cid)) crc1 = Image.core.crc32(data, Image.core.crc32(cid))
crc2 = i16(self.fp.read(2)), i16(self.fp.read(2)) crc2 = i16(self.fp.read(2)), i16(self.fp.read(2))
if crc1 != crc2: if crc1 != crc2:
raise SyntaxError("broken PNG file (bad header checksum in %r)" raise PILReadError("Bad header checksum in %r)" % (cid))
% cid)
except struct.error: except struct.error:
raise SyntaxError("broken PNG file (incomplete checksum in %r)" raise PILReadError("Incomplete checksum in %r" % (cid))
% cid)
def crc_skip(self, cid, data): def crc_skip(self, cid, data):
"Read checksum. Used if the C module is not present" "Read checksum. Used if the C module is not present"
@ -313,8 +310,7 @@ class PngStream(ChunkStream):
logger.debug("Compression method %s", i8(s[i])) logger.debug("Compression method %s", i8(s[i]))
comp_method = i8(s[i]) comp_method = i8(s[i])
if comp_method != 0: if comp_method != 0:
raise SyntaxError("Unknown compression method %s in iCCP chunk" % raise PILReadError("Unknown compression method %s" % (comp_method))()
comp_method)
try: try:
icc_profile = _safe_zlib_decompress(s[i+2:]) icc_profile = _safe_zlib_decompress(s[i+2:])
except ValueError: except ValueError:
@ -339,7 +335,7 @@ class PngStream(ChunkStream):
if i8(s[12]): if i8(s[12]):
self.im_info["interlace"] = 1 self.im_info["interlace"] = 1
if i8(s[11]): if i8(s[11]):
raise SyntaxError("unknown filter category") raise PILReadError("unknown filter category")
return s return s
def chunk_IDAT(self, pos, length): def chunk_IDAT(self, pos, length):
@ -437,7 +433,7 @@ class PngStream(ChunkStream):
else: else:
comp_method = 0 comp_method = 0
if comp_method != 0: if comp_method != 0:
raise SyntaxError("Unknown compression method %s in zTXt chunk" % raise PILReadError("Unknown compression method %s in zTXt chunk" %
comp_method) comp_method)
try: try:
v = _safe_zlib_decompress(v[1:]) v = _safe_zlib_decompress(v[1:])
@ -520,7 +516,7 @@ class PngImageFile(ImageFile.ImageFile):
def _open(self): def _open(self):
if self.fp.read(8) != _MAGIC: if self.fp.read(8) != _MAGIC:
raise SyntaxError("not a PNG file") raise InvalidFileType("not a PNG file")
# #
# Parse headers up to the first IDAT chunk # Parse headers up to the first IDAT chunk

View File

@ -14,10 +14,10 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
import string import string
from PIL import Image, ImageFile from PIL import Image, ImageFile
from .exceptions import InvalidFileType, PILReadError, PILWriteError
__version__ = "0.2" __version__ = "0.2"
@ -31,7 +31,7 @@ try:
if locale_enc is None: if locale_enc is None:
locale_lang, locale_enc = locale.getdefaultlocale() locale_lang, locale_enc = locale.getdefaultlocale()
b_whitespace = b_whitespace.decode(locale_enc) b_whitespace = b_whitespace.decode(locale_enc)
except: except Exception:
pass pass
b_whitespace = b_whitespace.encode('ascii', 'ignore') b_whitespace = b_whitespace.encode('ascii', 'ignore')
@ -67,10 +67,10 @@ class PpmImageFile(ImageFile.ImageFile):
if not c or c in b_whitespace: if not c or c in b_whitespace:
break break
if c > b'\x79': if c > b'\x79':
raise ValueError("Expected ASCII value, found binary") raise PILReadError("Expected ASCII value, found binary")
s = s + c s = s + c
if (len(s) > 9): if (len(s) > 9):
raise ValueError("Expected int, got > 9 digits") raise PILReadError("Expected int, got > 9 digits")
return s return s
def _open(self): def _open(self):
@ -78,7 +78,7 @@ class PpmImageFile(ImageFile.ImageFile):
# check magic # check magic
s = self.fp.read(1) s = self.fp.read(1)
if s != b"P": if s != b"P":
raise SyntaxError("not a PPM file") raise InvalidFileType("not a PPM file")
mode = MODES[self._token(s)] mode = MODES[self._token(s)]
if mode == "1": if mode == "1":
@ -94,7 +94,7 @@ class PpmImageFile(ImageFile.ImageFile):
if s not in b_whitespace: if s not in b_whitespace:
break break
if s == b"": if s == b"":
raise ValueError("File does not extend beyond magic number") raise PILReadError("File does not extend beyond magic number")
if s != b"#": if s != b"#":
break break
s = self.fp.readline() s = self.fp.readline()
@ -109,7 +109,7 @@ class PpmImageFile(ImageFile.ImageFile):
# maxgrey # maxgrey
if s > 255: if s > 255:
if not mode == 'L': if not mode == 'L':
raise ValueError("Too many colors for band: %s" % s) raise PILReadError("Too many colors for band: %s" % s)
if s < 2**16: if s < 2**16:
self.mode = 'I' self.mode = 'I'
rawmode = 'I;16B' rawmode = 'I;16B'
@ -142,7 +142,7 @@ def _save(im, fp, filename):
elif im.mode == "RGBA": elif im.mode == "RGBA":
rawmode, head = "RGB", b"P6" rawmode, head = "RGB", b"P6"
else: else:
raise IOError("cannot write mode %s as PPM" % im.mode) raise PILWriteError("cannot write mode %s as PPM" % im.mode)
fp.write(head + ("\n%d %d\n" % im.size).encode('ascii')) fp.write(head + ("\n%d %d\n" % im.size).encode('ascii'))
if head == b"P6": if head == b"P6":
fp.write(b"255\n") fp.write(b"255\n")

View File

@ -16,9 +16,11 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
__version__ = "0.4"
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.4"
MODES = { MODES = {
# (photoshop mode, bits) -> (pil mode, required channels) # (photoshop mode, bits) -> (pil mode, required channels)
@ -57,7 +59,6 @@ class PsdImageFile(ImageFile.ImageFile):
format_description = "Adobe Photoshop" format_description = "Adobe Photoshop"
def _open(self): def _open(self):
read = self.fp.read read = self.fp.read
# #
@ -65,7 +66,7 @@ class PsdImageFile(ImageFile.ImageFile):
s = read(26) s = read(26)
if s[:4] != b"8BPS" or i16(s[4:]) != 1: if s[:4] != b"8BPS" or i16(s[4:]) != 1:
raise SyntaxError("not a PSD file") raise InvalidFileType("not a PSD file")
psd_bits = i16(s[22:]) psd_bits = i16(s[22:])
psd_channels = i16(s[12:]) psd_channels = i16(s[12:])
@ -74,7 +75,7 @@ class PsdImageFile(ImageFile.ImageFile):
mode, channels = MODES[(psd_mode, psd_bits)] mode, channels = MODES[(psd_mode, psd_bits)]
if channels > psd_channels: if channels > psd_channels:
raise IOError("not enough channels") raise PILReadError("not enough channels")
self.mode = mode self.mode = mode
self.size = i32(s[18:]), i32(s[14:]) self.size = i32(s[18:]), i32(s[14:])

View File

@ -20,11 +20,8 @@
# Access.c implementation. # Access.c implementation.
# #
from __future__ import print_function
import logging import logging
import sys import sys
from cffi import FFI from cffi import FFI

View File

@ -14,12 +14,6 @@
# Copyright (c) 2004 by Fredrik Lundh. # Copyright (c) 2004 by Fredrik Lundh.
# #
##
# Image plugin for the Spider image format. This format is is used
# by the SPIDER software, in processing image data from electron
# microscopy and tomography.
##
# #
# SpiderImagePlugin.py # SpiderImagePlugin.py
# #
@ -33,12 +27,11 @@
# http://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html # http://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
# #
from __future__ import print_function
from PIL import Image, ImageFile from PIL import Image, ImageFile
import os import os
import struct import struct
import sys import sys
from .exceptions import InvalidFileType, PILReadError
def isInt(f): def isInt(f):
@ -75,9 +68,9 @@ def isSpiderHeader(t):
labrec = int(h[13]) # no. records in file header labrec = int(h[13]) # no. records in file header
labbyt = int(h[22]) # total no. of bytes in header labbyt = int(h[22]) # total no. of bytes in header
lenbyt = int(h[23]) # record length in bytes lenbyt = int(h[23]) # record length in bytes
# print("labrec = %d, labbyt = %d, lenbyt = %d" % (labrec,labbyt,lenbyt))
if labbyt != (labrec * lenbyt): if labbyt != (labrec * lenbyt):
return 0 return 0
# looks like a valid header # looks like a valid header
return labbyt return labbyt
@ -112,14 +105,14 @@ class SpiderImageFile(ImageFile.ImageFile):
t = struct.unpack('<27f', f) # little-endian t = struct.unpack('<27f', f) # little-endian
hdrlen = isSpiderHeader(t) hdrlen = isSpiderHeader(t)
if hdrlen == 0: if hdrlen == 0:
raise SyntaxError("not a valid Spider file") raise InvalidFileType("not a valid Spider file")
except struct.error: except struct.error:
raise SyntaxError("not a valid Spider file") raise InvalidFileType("not a valid Spider file")
h = (99,) + t # add 1 value : spider header index starts at 1 h = (99,) + t # add 1 value : spider header index starts at 1
iform = int(h[5]) iform = int(h[5])
if iform != 1: if iform != 1:
raise SyntaxError("not a Spider 2D image") raise InvalidFileType("not a Spider 2D image")
self.size = int(h[12]), int(h[2]) # size in pixels (width, height) self.size = int(h[12]), int(h[2]) # size in pixels (width, height)
self.istack = int(h[24]) self.istack = int(h[24])
@ -142,7 +135,7 @@ class SpiderImageFile(ImageFile.ImageFile):
offset = hdrlen + self.stkoffset offset = hdrlen + self.stkoffset
self.istack = 2 # So Image knows it's still a stack self.istack = 2 # So Image knows it's still a stack
else: else:
raise SyntaxError("inconsistent stack header values") raise PILReadError("inconsistent stack header values")
if self.bigendian: if self.bigendian:
self.rawmode = "F;32BF" self.rawmode = "F;32BF"
@ -195,30 +188,6 @@ class SpiderImageFile(ImageFile.ImageFile):
return ImageTk.PhotoImage(self.convert2byte(), palette=256) return ImageTk.PhotoImage(self.convert2byte(), palette=256)
# --------------------------------------------------------------------
# Image series
# given a list of filenames, return a list of images
def loadImageSeries(filelist=None):
" create a list of Image.images for use in montage "
if filelist is None or len(filelist) < 1:
return
imglist = []
for img in filelist:
if not os.path.exists(img):
print("unable to find %s" % img)
continue
try:
im = Image.open(img).convert2byte()
except:
if not isSpiderImage(img):
print(img + " is not a Spider image file")
continue
im.info['filename'] = img
imglist.append(im)
return imglist
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# For saving images in Spider format # For saving images in Spider format
@ -288,34 +257,3 @@ def _save_spider(im, fp, filename):
Image.register_open(SpiderImageFile.format, SpiderImageFile) Image.register_open(SpiderImageFile.format, SpiderImageFile)
Image.register_save(SpiderImageFile.format, _save_spider) Image.register_save(SpiderImageFile.format, _save_spider)
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python SpiderImagePlugin.py [infile] [outfile]")
sys.exit()
filename = sys.argv[1]
if not isSpiderImage(filename):
print("input image must be in Spider format")
sys.exit()
outfile = ""
if len(sys.argv[1:]) > 1:
outfile = sys.argv[2]
im = Image.open(filename)
print("image: " + str(im))
print("format: " + str(im.format))
print("size: " + str(im.size))
print("mode: " + str(im.mode))
print("max, min: ", end=' ')
print(im.getextrema())
if outfile != "":
# perform some image operation
im = im.transpose(Image.FLIP_LEFT_RIGHT)
print(
"saving a flipped version of %s as %s " %
(os.path.basename(filename), outfile))
im.save(outfile, SpiderImageFile.format)

View File

@ -16,8 +16,9 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType
__version__ = "0.3" __version__ = "0.3"
@ -56,18 +57,18 @@ class SunImageFile(ImageFile.ImageFile):
# HEAD # HEAD
s = self.fp.read(32) s = self.fp.read(32)
if i32(s) != 0x59a66a95: if i32(s) != 0x59a66a95:
raise SyntaxError("not an SUN raster file") raise InvalidFileType("not a SUN raster file")
offset = 32 offset = 32
self.size = i32(s[4:8]), i32(s[8:12]) self.size = i32(s[4:8]), i32(s[8:12])
depth = i32(s[12:16]) depth = i32(s[12:16])
data_length = i32(s[16:20]) # unreliable, ignore. data_length = i32(s[16:20]) # unreliable, ignore.
file_type = i32(s[20:24]) file_type = i32(s[20:24])
palette_type = i32(s[24:28]) # 0: None, 1: RGB, 2: Raw/arbitrary palette_type = i32(s[24:28]) # 0: None, 1: RGB, 2: Raw/arbitrary
palette_length = i32(s[28:32]) palette_length = i32(s[28:32])
if depth == 1: if depth == 1:
self.mode, rawmode = "1", "1;I" self.mode, rawmode = "1", "1;I"
elif depth == 4: elif depth == 4:
@ -85,23 +86,23 @@ class SunImageFile(ImageFile.ImageFile):
else: else:
self.mode, rawmode = 'RGB', 'BGRX' self.mode, rawmode = 'RGB', 'BGRX'
else: else:
raise SyntaxError("Unsupported Mode/Bit Depth") raise NotImplementedError("Unsupported Mode/Bit Depth")
if palette_length: if palette_length:
if palette_length > 1024: if palette_length > 1024:
raise SyntaxError("Unsupported Color Palette Length") raise NotImplementedError("Unsupported Color Palette Length")
if palette_type != 1: if palette_type != 1:
raise SyntaxError("Unsupported Palette Type") raise NotImplementedError("Unsupported Palette Type")
offset = offset + palette_length offset = offset + palette_length
self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length)) self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length))
if self.mode == "L": if self.mode == "L":
self.mode = "P" self.mode = "P"
rawmode = rawmode.replace('L', 'P') rawmode = rawmode.replace('L', 'P')
# 16 bit boundaries on stride # 16 bit boundaries on stride
stride = ((self.size[0] * depth + 15) // 16) * 2 stride = ((self.size[0] * depth + 15) // 16) * 2
# file type: Type is the version (or flavor) of the bitmap # file type: Type is the version (or flavor) of the bitmap
# file. The following values are typically found in the Type # file. The following values are typically found in the Type
@ -126,8 +127,9 @@ class SunImageFile(ImageFile.ImageFile):
elif file_type == 2: elif file_type == 2:
self.tile = [("sun_rle", (0, 0)+self.size, offset, rawmode)] self.tile = [("sun_rle", (0, 0)+self.size, offset, rawmode)]
else: else:
raise SyntaxError('Unsupported Sun Raster file type') raise NotImplementedError('Unsupported Sun Raster file type')
# #
# registry # registry

View File

@ -16,8 +16,9 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType, PILReadError, PILWriteError
__version__ = "0.3" __version__ = "0.3"
@ -69,7 +70,7 @@ class TgaImageFile(ImageFile.ImageFile):
if colormaptype not in (0, 1) or\ if colormaptype not in (0, 1) or\
self.size[0] <= 0 or self.size[1] <= 0 or\ self.size[0] <= 0 or self.size[1] <= 0 or\
depth not in (1, 8, 16, 24, 32): depth not in (1, 8, 16, 24, 32):
raise SyntaxError("not a TGA file") raise InvalidFileType("not a TGA file")
# image mode # image mode
if imagetype in (3, 11): if imagetype in (3, 11):
@ -83,7 +84,7 @@ class TgaImageFile(ImageFile.ImageFile):
if depth == 32: if depth == 32:
self.mode = "RGBA" self.mode = "RGBA"
else: else:
raise SyntaxError("unknown TGA mode") raise PILReadError("unknown TGA mode")
# orientation # orientation
orientation = flags & 0x30 orientation = flags & 0x30
@ -92,7 +93,7 @@ class TgaImageFile(ImageFile.ImageFile):
elif not orientation: elif not orientation:
orientation = -1 orientation = -1
else: else:
raise SyntaxError("unknown TGA orientation") raise PILReadError("unknown TGA orientation")
self.info["orientation"] = orientation self.info["orientation"] = orientation
@ -150,7 +151,7 @@ def _save(im, fp, filename, check=0):
try: try:
rawmode, bits, colormaptype, imagetype = SAVE[im.mode] rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
except KeyError: except KeyError:
raise IOError("cannot write mode %s as TGA" % im.mode) raise PILWriteError("cannot write mode %s as TGA" % im.mode)
if check: if check:
return check return check

View File

@ -41,23 +41,18 @@
from __future__ import division, print_function from __future__ import division, print_function
from PIL import Image, ImageFile
from PIL import ImagePalette
from PIL import _binary
from PIL import TiffTags
import collections import collections
from fractions import Fraction
from numbers import Number, Rational
import io import io
import itertools import itertools
import os import os
import struct import struct
import sys import sys
import warnings import warnings
from fractions import Fraction
from numbers import Number, Rational
from .TiffTags import TYPES from .TiffTags import TYPES
from PIL import Image, ImageFile, ImagePalette, TiffTags, _binary
from .exceptions import InvalidFileType
__version__ = "1.3.5" __version__ = "1.3.5"
@ -436,14 +431,14 @@ class ImageFileDirectory_v2(collections.MutableMapping):
:param prefix: Override the endianness of the file. :param prefix: Override the endianness of the file.
""" """
if ifh[:4] not in PREFIXES: if ifh[:4] not in PREFIXES:
raise SyntaxError("not a TIFF file (header %r not valid)" % ifh) raise InvalidFileType("not a TIFF file (header %r not valid)" % ifh)
self._prefix = prefix if prefix is not None else ifh[:2] self._prefix = prefix if prefix is not None else ifh[:2]
if self._prefix == MM: if self._prefix == MM:
self._endian = ">" self._endian = ">"
elif self._prefix == II: elif self._prefix == II:
self._endian = "<" self._endian = "<"
else: else:
raise SyntaxError("not a TIFF IFD") raise InvalidFileType("not a TIFF IFD")
self.reset() self.reset()
self.next, = self._unpack("L", ifh[4:]) self.next, = self._unpack("L", ifh[4:])
self._legacy_api = False self._legacy_api = False
@ -1156,7 +1151,7 @@ class TiffImageFile(ImageFile.ImageFile):
except KeyError: except KeyError:
if DEBUG: if DEBUG:
print("- unsupported format") print("- unsupported format")
raise SyntaxError("unknown pixel mode") raise PILReadError("unknown pixel mode")
if DEBUG: if DEBUG:
print("- raw mode:", rawmode) print("- raw mode:", rawmode)
@ -1276,7 +1271,7 @@ class TiffImageFile(ImageFile.ImageFile):
else: else:
if DEBUG: if DEBUG:
print("- unsupported data organization") print("- unsupported data organization")
raise SyntaxError("unknown data organization") raise PILReadError("unknown data organization")
# Fix up info. # Fix up info.
if ICCPROFILE in self.tag_v2: if ICCPROFILE in self.tag_v2:

View File

@ -21,8 +21,6 @@
# http://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml # http://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml
# and has been tested with a few sample files found using google. # and has been tested with a few sample files found using google.
from __future__ import print_function
from PIL import Image, _binary from PIL import Image, _binary
try: try:

View File

@ -19,9 +19,9 @@
# http://wvware.sourceforge.net/caolan/index.html # http://wvware.sourceforge.net/caolan/index.html
# http://wvware.sourceforge.net/caolan/ora-wmf.html # http://wvware.sourceforge.net/caolan/ora-wmf.html
from __future__ import print_function
from PIL import Image, ImageFile, _binary from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType
__version__ = "0.2" __version__ = "0.2"
@ -110,11 +110,9 @@ class WmfStubImageFile(ImageFile.StubImageFile):
self.info["dpi"] = 72 self.info["dpi"] = 72
# print(self.mode, self.size, self.info)
# sanity check (standard metafile header) # sanity check (standard metafile header)
if s[22:26] != b"\x01\x00\t\x00": if s[22:26] != b"\x01\x00\t\x00":
raise SyntaxError("Unsupported WMF file format") raise NotImplementedError("Unsupported WMF file format")
elif dword(s) == 1 and s[40:44] == b" EMF": elif dword(s) == 1 and s[40:44] == b" EMF":
# enhanced metafile # enhanced metafile
@ -143,7 +141,7 @@ class WmfStubImageFile(ImageFile.StubImageFile):
self.info["dpi"] = xdpi, ydpi self.info["dpi"] = xdpi, ydpi
else: else:
raise SyntaxError("Unsupported file format") raise InvalidFileType("Not a WMF file")
self.mode = "RGB" self.mode = "RGB"
self.size = size self.size = size

View File

@ -18,6 +18,8 @@
# #
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.1" __version__ = "0.1"
@ -46,10 +48,9 @@ class XVThumbImageFile(ImageFile.ImageFile):
format_description = "XV thumbnail image" format_description = "XV thumbnail image"
def _open(self): def _open(self):
# check magic # check magic
if self.fp.read(6) != _MAGIC: if self.fp.read(6) != _MAGIC:
raise SyntaxError("not an XV thumbnail file") raise InvalidFileType("not an XV thumbnail file")
# Skip to beginning of next line # Skip to beginning of next line
self.fp.readline() self.fp.readline()
@ -58,7 +59,7 @@ class XVThumbImageFile(ImageFile.ImageFile):
while True: while True:
s = self.fp.readline() s = self.fp.readline()
if not s: if not s:
raise SyntaxError("Unexpected EOF reading XV thumbnail file") raise PILReadError("Unexpected EOF reading XV thumbnail file")
if s[0] != b'#': if s[0] != b'#':
break break

View File

@ -18,6 +18,8 @@
import re import re
from PIL import Image, ImageFile, ImagePalette from PIL import Image, ImageFile, ImagePalette
from PIL._binary import i8, o8 from PIL._binary import i8, o8
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.2" __version__ = "0.2"
@ -40,13 +42,13 @@ class XpmImageFile(ImageFile.ImageFile):
def _open(self): def _open(self):
if not _accept(self.fp.read(9)): if not _accept(self.fp.read(9)):
raise SyntaxError("not an XPM file") raise InvalidFileType("not an XPM file")
# skip forward to next string # skip forward to next string
while True: while True:
s = self.fp.readline() s = self.fp.readline()
if not s: if not s:
raise SyntaxError("broken XPM file") raise PILReadError("broken XPM file")
m = xpm_head.match(s) m = xpm_head.match(s)
if m: if m:
break break

37
PIL/exceptions.py Normal file
View File

@ -0,0 +1,37 @@
"""
PIL Exceptions
"""
class PILError(Exception):
"""
Base exception for all PIL exceptions
"""
pass
class PILReadError(PILError):
"""
Some error happened while reading a file.
"""
pass
class InvalidFileType(PILReadError):
"""
The given file is not of the expected type.
"""
class NoPluginFound(PILError):
"""
No plugin was found for the given format.
"""
pass
class PILWriteError(PILError):
"""
Some error happened while writing a file.
"""
pass

View File

@ -1,12 +1,10 @@
""" """
Helper functions. Helper functions.
""" """
from __future__ import print_function import os
import sys import sys
import tempfile import tempfile
import os
import unittest import unittest
from PIL import Image, ImageMath from PIL import Image, ImageMath

View File

@ -7,6 +7,7 @@ import traceback
import sys import sys
sys.path.insert(0, ".") sys.path.insert(0, ".")
for file in glob.glob("PIL/*.py"): for file in glob.glob("PIL/*.py"):
module = os.path.basename(file)[:-3] module = os.path.basename(file)[:-3]
try: try:

View File

@ -1,8 +1,7 @@
from __future__ import print_function import os
from PIL import Image
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image
import os
base = os.path.join('Tests', 'images', 'bmp') base = os.path.join('Tests', 'images', 'bmp')
@ -22,7 +21,6 @@ class TestBmpReference(PillowTestCase):
im.load() im.load()
except Exception: # as msg: except Exception: # as msg:
pass pass
# print("Bad Image %s: %s" %(f,msg))
def test_questionable(self): def test_questionable(self):
""" These shouldn't crash/dos, but it's not well defined that these """ These shouldn't crash/dos, but it's not well defined that these
@ -47,7 +45,6 @@ class TestBmpReference(PillowTestCase):
except Exception: # as msg: except Exception: # as msg:
if os.path.basename(f) in supported: if os.path.basename(f) in supported:
raise raise
# print("Bad Image %s: %s" %(f,msg))
def test_good(self): def test_good(self):
""" These should all work. There's a set of target files in the """ These should all work. There's a set of target files in the

View File

@ -1,7 +1,7 @@
from helper import unittest, PillowTestCase, hopper
from PIL import Image, BmpImagePlugin
import io import io
from PIL import Image, BmpImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper
class TestFileBmp(PillowTestCase): class TestFileBmp(PillowTestCase):
@ -27,7 +27,7 @@ class TestFileBmp(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp: with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: BmpImagePlugin.BmpImageFile(fp)) lambda: BmpImagePlugin.BmpImageFile(fp))
def test_save_to_bytes(self): def test_save_to_bytes(self):

View File

@ -1,6 +1,6 @@
from helper import unittest, PillowTestCase
from PIL import BufrStubImagePlugin from PIL import BufrStubImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase
class TestFileBufrStub(PillowTestCase): class TestFileBufrStub(PillowTestCase):
@ -8,7 +8,7 @@ class TestFileBufrStub(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: lambda:
BufrStubImagePlugin.BufrStubImageFile(invalid_file)) BufrStubImagePlugin.BufrStubImageFile(invalid_file))

View File

@ -1,6 +1,7 @@
from PIL import Image, CurImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image, CurImagePlugin
TEST_FILE = "Tests/images/deerstalker.cur" TEST_FILE = "Tests/images/deerstalker.cur"
@ -20,7 +21,7 @@ class TestFileCur(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: CurImagePlugin.CurImageFile(invalid_file)) lambda: CurImagePlugin.CurImageFile(invalid_file))
no_cursors_file = "Tests/images/no_cursors.cur" no_cursors_file = "Tests/images/no_cursors.cur"

View File

@ -1,6 +1,8 @@
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from PIL import Image, DcxImagePlugin from PIL import Image, DcxImagePlugin
from PIL.exceptions import InvalidFileType
# Created with ImageMagick: convert hopper.ppm hopper.dcx # Created with ImageMagick: convert hopper.ppm hopper.dcx
TEST_FILE = "Tests/images/hopper.dcx" TEST_FILE = "Tests/images/hopper.dcx"
@ -22,7 +24,7 @@ class TestFileDcx(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp: with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: DcxImagePlugin.DcxImageFile(fp)) lambda: DcxImagePlugin.DcxImageFile(fp))
def test_tell(self): def test_tell(self):

View File

@ -1,7 +1,8 @@
import io
from PIL import Image, EpsImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image, EpsImagePlugin
import io
# Our two EPS test files (they are identical except for their bounding boxes) # Our two EPS test files (they are identical except for their bounding boxes)
file1 = "Tests/images/zero_bb.eps" file1 = "Tests/images/zero_bb.eps"
@ -54,7 +55,7 @@ class TestFileEps(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: EpsImagePlugin.EpsImageFile(invalid_file)) lambda: EpsImagePlugin.EpsImageFile(invalid_file))
def test_cmyk(self): def test_cmyk(self):

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import FitsStubImagePlugin from PIL import FitsStubImagePlugin
from PIL.exceptions import InvalidFileType
class TestFileFitsStub(PillowTestCase): class TestFileFitsStub(PillowTestCase):
@ -8,7 +9,7 @@ class TestFileFitsStub(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: lambda:
FitsStubImagePlugin.FITSStubImageFile(invalid_file)) FitsStubImagePlugin.FITSStubImageFile(invalid_file))

View File

@ -1,6 +1,7 @@
from PIL import Image, FliImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image, FliImagePlugin
# sample ppm stream # sample ppm stream
# created as an export of a palette image from Gimp2.6 # created as an export of a palette image from Gimp2.6
@ -20,7 +21,7 @@ class TestFileFli(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: FliImagePlugin.FliImageFile(invalid_file)) lambda: FliImagePlugin.FliImageFile(invalid_file))
def test_n_frames(self): def test_n_frames(self):

View File

@ -1,6 +1,6 @@
from helper import unittest, PillowTestCase
from PIL import FpxImagePlugin from PIL import FpxImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase
class TestFileFpx(PillowTestCase): class TestFileFpx(PillowTestCase):
@ -8,12 +8,12 @@ class TestFileFpx(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
# Test an invalid OLE file # Test an invalid OLE file
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: FpxImagePlugin.FpxImageFile(invalid_file)) lambda: FpxImagePlugin.FpxImageFile(invalid_file))
# Test a valid OLE file, but not an FPX file # Test a valid OLE file, but not an FPX file
ole_file = "Tests/images/test-ole-file.doc" ole_file = "Tests/images/test-ole-file.doc"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: FpxImagePlugin.FpxImageFile(ole_file)) lambda: FpxImagePlugin.FpxImageFile(ole_file))

View File

@ -1,14 +1,14 @@
from helper import unittest, PillowTestCase
from PIL import Image, GbrImagePlugin from PIL import Image, GbrImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase
class TestFileGbr(PillowTestCase): class TestFileGbr(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/no_cursors.cur"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: GbrImagePlugin.GbrImageFile(invalid_file)) lambda: GbrImagePlugin.GbrImageFile(invalid_file))
def test_gbr_file(self): def test_gbr_file(self):

View File

@ -1,9 +1,8 @@
from io import BytesIO
from PIL import Image, GifImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper, netpbm_available from helper import unittest, PillowTestCase, hopper, netpbm_available
from PIL import Image
from PIL import GifImagePlugin
from io import BytesIO
codecs = dir(Image.core) codecs = dir(Image.core)
@ -31,7 +30,7 @@ class TestFileGif(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: GifImagePlugin.GifImageFile(invalid_file)) lambda: GifImagePlugin.GifImageFile(invalid_file))
def test_optimize(self): def test_optimize(self):
@ -425,7 +424,7 @@ class TestFileGif(PillowTestCase):
reloaded = Image.open(out) reloaded = Image.open(out)
self.assertEqual(reloaded.info['transparency'], 253) self.assertEqual(reloaded.info['transparency'], 253)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL.GimpPaletteFile import GimpPaletteFile from PIL.GimpPaletteFile import GimpPaletteFile
from PIL.exceptions import InvalidFileType, PILReadError
class TestImage(PillowTestCase): class TestImage(PillowTestCase):
@ -10,13 +11,13 @@ class TestImage(PillowTestCase):
GimpPaletteFile(fp) GimpPaletteFile(fp)
with open('Tests/images/hopper.jpg', 'rb') as fp: with open('Tests/images/hopper.jpg', 'rb') as fp:
self.assertRaises(SyntaxError, lambda: GimpPaletteFile(fp)) self.assertRaises(InvalidFileType, lambda: GimpPaletteFile(fp))
with open('Tests/images/bad_palette_file.gpl', 'rb') as fp: with open('Tests/images/bad_palette_file.gpl', 'rb') as fp:
self.assertRaises(SyntaxError, lambda: GimpPaletteFile(fp)) self.assertRaises(PILReadError, lambda: GimpPaletteFile(fp))
with open('Tests/images/bad_palette_entry.gpl', 'rb') as fp: with open('Tests/images/bad_palette_entry.gpl', 'rb') as fp:
self.assertRaises(ValueError, lambda: GimpPaletteFile(fp)) self.assertRaises(PILReadError, lambda: GimpPaletteFile(fp))
def test_get_palette(self): def test_get_palette(self):
# Arrange # Arrange

View File

@ -1,6 +1,6 @@
from helper import unittest, PillowTestCase
from PIL import GribStubImagePlugin from PIL import GribStubImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase
class TestFileGribStub(PillowTestCase): class TestFileGribStub(PillowTestCase):
@ -8,7 +8,7 @@ class TestFileGribStub(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: lambda:
GribStubImagePlugin.GribStubImageFile(invalid_file)) GribStubImagePlugin.GribStubImageFile(invalid_file))

View File

@ -1,6 +1,6 @@
from helper import unittest, PillowTestCase
from PIL import Hdf5StubImagePlugin from PIL import Hdf5StubImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase
class TestFileHdf5Stub(PillowTestCase): class TestFileHdf5Stub(PillowTestCase):
@ -8,7 +8,7 @@ class TestFileHdf5Stub(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
test_file = "Tests/images/flower.jpg" test_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: lambda:
Hdf5StubImagePlugin.HDF5StubImageFile(test_file)) Hdf5StubImagePlugin.HDF5StubImageFile(test_file))

View File

@ -1,7 +1,8 @@
from helper import unittest, PillowTestCase, hopper
import io import io
from PIL import Image, IcoImagePlugin from PIL import Image, IcoImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper
# sample ppm stream # sample ppm stream
TEST_ICO_FILE = "Tests/images/hopper.ico" TEST_ICO_FILE = "Tests/images/hopper.ico"
@ -18,7 +19,7 @@ class TestFileIco(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp: with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: IcoImagePlugin.IcoImageFile(fp)) lambda: IcoImagePlugin.IcoImageFile(fp))
def test_save_to_bytes(self): def test_save_to_bytes(self):

View File

@ -1,6 +1,8 @@
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from PIL import Image, ImImagePlugin from PIL import Image, ImImagePlugin
from PIL.exceptions import InvalidFileType
# sample im # sample im
TEST_IM = "Tests/images/hopper.im" TEST_IM = "Tests/images/hopper.im"
@ -43,7 +45,7 @@ class TestFileIm(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: ImImagePlugin.ImImageFile(invalid_file)) lambda: ImImagePlugin.ImImageFile(invalid_file))

View File

@ -39,27 +39,6 @@ class TestFileIptc(PillowTestCase):
# Assert # Assert
self.assertEqual(ret, 97) self.assertEqual(ret, 97)
def test_dump(self):
# Arrange
c = b"abc"
# Temporarily redirect stdout
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# Act
IptcImagePlugin.dump(c)
# Reset stdout
sys.stdout = old_stdout
# Assert
self.assertEqual(mystdout.getvalue(), "61 62 63 \n")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,7 +1,9 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image, Jpeg2KImagePlugin
from io import BytesIO from io import BytesIO
from PIL import Image, Jpeg2KImagePlugin
from PIL.exceptions import InvalidFileType
codecs = dir(Image.core) codecs = dir(Image.core)
@ -43,7 +45,7 @@ class TestFileJpeg2k(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: lambda:
Jpeg2KImagePlugin.Jpeg2KImageFile(invalid_file)) Jpeg2KImagePlugin.Jpeg2KImageFile(invalid_file))

View File

@ -1,6 +1,6 @@
from helper import unittest, PillowTestCase
from PIL import McIdasImagePlugin from PIL import McIdasImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase
class TestFileMcIdas(PillowTestCase): class TestFileMcIdas(PillowTestCase):
@ -8,7 +8,7 @@ class TestFileMcIdas(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: lambda:
McIdasImagePlugin.McIdasImageFile(invalid_file)) McIdasImagePlugin.McIdasImageFile(invalid_file))

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import MicImagePlugin from PIL import MicImagePlugin
from PIL.exceptions import PILReadError, InvalidFileType
class TestFileMic(PillowTestCase): class TestFileMic(PillowTestCase):
@ -8,12 +9,12 @@ class TestFileMic(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
# Test an invalid OLE file # Test an invalid OLE file
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: MicImagePlugin.MicImageFile(invalid_file)) lambda: MicImagePlugin.MicImageFile(invalid_file))
# Test a valid OLE file, but not a MIC file # Test a valid OLE file, but not a MIC file
ole_file = "Tests/images/test-ole-file.doc" ole_file = "Tests/images/test-ole-file.doc"
self.assertRaises(SyntaxError, self.assertRaises(PILReadError,
lambda: MicImagePlugin.MicImageFile(ole_file)) lambda: MicImagePlugin.MicImageFile(ole_file))

View File

@ -1,6 +1,7 @@
from PIL import Image, MspImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from PIL import Image, MspImagePlugin
TEST_FILE = "Tests/images/hopper.msp" TEST_FILE = "Tests/images/hopper.msp"
@ -21,7 +22,7 @@ class TestFileMsp(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: MspImagePlugin.MspImageFile(invalid_file)) lambda: MspImagePlugin.MspImageFile(invalid_file))
def test_open(self): def test_open(self):

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from PIL import Image, ImageFile, PcxImagePlugin from PIL import Image, ImageFile, PcxImagePlugin
from PIL.exceptions import InvalidFileType
class TestFilePcx(PillowTestCase): class TestFilePcx(PillowTestCase):
@ -22,7 +23,7 @@ class TestFilePcx(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: PcxImagePlugin.PcxImageFile(invalid_file)) lambda: PcxImagePlugin.PcxImageFile(invalid_file))
def test_odd(self): def test_odd(self):

View File

@ -1,11 +1,9 @@
import zlib
from io import BytesIO
from PIL import Image, ImageFile, PngImagePlugin
from PIL.exceptions import InvalidFileType, PILReadError
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from io import BytesIO
from PIL import Image
from PIL import ImageFile
from PIL import PngImagePlugin
import zlib
codecs = dir(Image.core) codecs = dir(Image.core)
@ -84,7 +82,7 @@ class TestFilePng(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: PngImagePlugin.PngImageFile(invalid_file)) lambda: PngImagePlugin.PngImageFile(invalid_file))
def test_broken(self): def test_broken(self):
@ -317,7 +315,7 @@ class TestFilePng(PillowTestCase):
im = Image.open(BytesIO(test_file)) im = Image.open(BytesIO(test_file))
self.assertTrue(im.fp is not None) self.assertTrue(im.fp is not None)
self.assertRaises((IOError, SyntaxError), im.verify) self.assertRaises((IOError, PILReadError), im.verify)
def test_verify_ignores_crc_error(self): def test_verify_ignores_crc_error(self):
# check ignores crc errors in ancillary chunks # check ignores crc errors in ancillary chunks
@ -326,7 +324,7 @@ class TestFilePng(PillowTestCase):
broken_crc_chunk_data = chunk_data[:-1] + b'q' # break CRC broken_crc_chunk_data = chunk_data[:-1] + b'q' # break CRC
image_data = HEAD + broken_crc_chunk_data + TAIL image_data = HEAD + broken_crc_chunk_data + TAIL
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data)) self.assertRaises(PILReadError, PngImagePlugin.PngImageFile, BytesIO(image_data))
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
try: try:
@ -342,7 +340,7 @@ class TestFilePng(PillowTestCase):
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
try: try:
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data)) self.assertRaises(PILReadError, PngImagePlugin.PngImageFile, BytesIO(image_data))
finally: finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image from PIL import Image
from PIL.exceptions import PILReadError
# sample ppm stream # sample ppm stream
test_file = "Tests/images/hopper.ppm" test_file = "Tests/images/hopper.ppm"
@ -39,7 +40,7 @@ class TestFilePpm(PillowTestCase):
with open(path, 'w') as f: with open(path, 'w') as f:
f.write('P6') f.write('P6')
self.assertRaises(ValueError, lambda: Image.open(path)) self.assertRaises(IOError, lambda: Image.open(path))
def test_neg_ppm(self): def test_neg_ppm(self):

View File

@ -1,6 +1,8 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image, PsdImagePlugin from PIL import Image, PsdImagePlugin
from PIL.exceptions import InvalidFileType
# sample ppm stream # sample ppm stream
test_file = "Tests/images/hopper.psd" test_file = "Tests/images/hopper.psd"
@ -18,7 +20,7 @@ class TestImagePsd(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: PsdImagePlugin.PsdImageFile(invalid_file)) lambda: PsdImagePlugin.PsdImageFile(invalid_file))
def test_n_frames(self): def test_n_frames(self):

View File

@ -48,29 +48,6 @@ class TestImageSpider(PillowTestCase):
self.assertEqual(im.n_frames, 1) self.assertEqual(im.n_frames, 1)
self.assertFalse(im.is_animated) self.assertFalse(im.is_animated)
def test_loadImageSeries(self):
# Arrange
not_spider_file = "Tests/images/hopper.ppm"
file_list = [TEST_FILE, not_spider_file, "path/not_found.ext"]
# Act
img_list = SpiderImagePlugin.loadImageSeries(file_list)
# Assert
self.assertEqual(len(img_list), 1)
self.assertIsInstance(img_list[0], Image.Image)
self.assertEqual(img_list[0].size, (128, 128))
def test_loadImageSeries_no_input(self):
# Arrange
file_list = None
# Act
img_list = SpiderImagePlugin.loadImageSeries(file_list)
# Assert
self.assertEqual(img_list, None)
def test_isInt_not_a_number(self): def test_isInt_not_a_number(self):
# Arrange # Arrange
not_a_number = "a" not_a_number = "a"

View File

@ -1,8 +1,8 @@
import os
from PIL import Image, SunImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from PIL import Image, SunImagePlugin
import os
EXTRA_DIR = 'Tests/images/sunraster' EXTRA_DIR = 'Tests/images/sunraster'
@ -20,9 +20,9 @@ class TestFileSun(PillowTestCase):
self.assertEqual(im.size, (128, 128)) self.assertEqual(im.size, (128, 128))
self.assert_image_similar(im, hopper(), 5) # visually verified self.assert_image_similar(im, hopper(), 5) # visually verified
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: SunImagePlugin.SunImageFile(invalid_file)) lambda: SunImagePlugin.SunImageFile(invalid_file))
def test_im1(self): def test_im1(self):
@ -39,12 +39,12 @@ class TestFileSun(PillowTestCase):
in ('.sun', '.SUN', '.ras')) in ('.sun', '.SUN', '.ras'))
for path in files: for path in files:
with Image.open(path) as im: with Image.open(path) as im:
im.load() im.load()
self.assertIsInstance(im, SunImagePlugin.SunImageFile) self.assertIsInstance(im, SunImagePlugin.SunImageFile)
target_path = "%s.png" % os.path.splitext(path)[0] target_path = "%s.png" % os.path.splitext(path)[0]
#im.save(target_file) #im.save(target_file)
with Image.open(target_path) as target: with Image.open(target_path) as target:
self.assert_image_equal(im, target) self.assert_image_equal(im, target)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,7 +1,7 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image from PIL import Image
from PIL.exceptions import PILWriteError
class TestFileTga(PillowTestCase): class TestFileTga(PillowTestCase):
@ -42,7 +42,7 @@ class TestFileTga(PillowTestCase):
self.assertEqual(test_im.size, (100, 100)) self.assertEqual(test_im.size, (100, 100))
# Unsupported mode save # Unsupported mode save
self.assertRaises(IOError, lambda: im.convert("LA").save(test_file)) self.assertRaises(PILWriteError, lambda: im.convert("LA").save(test_file))
def test_save_rle(self): def test_save_rle(self):
test_file = "Tests/images/rgb32rle.tga" test_file = "Tests/images/rgb32rle.tga"
@ -61,7 +61,7 @@ class TestFileTga(PillowTestCase):
self.assertEqual(test_im.size, (199, 199)) self.assertEqual(test_im.size, (199, 199))
# Unsupported mode save # Unsupported mode save
self.assertRaises(IOError, lambda: im.convert("LA").save(test_file)) self.assertRaises(PILWriteError, lambda: im.convert("LA").save(test_file))
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,11 +1,10 @@
from __future__ import print_function
import logging import logging
from io import BytesIO
import struct import struct
from io import BytesIO
from PIL import Image, TiffImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper, py3 from helper import unittest, PillowTestCase, hopper, py3
from PIL import Image, TiffImagePlugin
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -116,11 +115,11 @@ class TestFileTiff(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: TiffImagePlugin.TiffImageFile(invalid_file)) lambda: TiffImagePlugin.TiffImageFile(invalid_file))
TiffImagePlugin.PREFIXES.append(b"\xff\xd8\xff\xe0") TiffImagePlugin.PREFIXES.append(b"\xff\xd8\xff\xe0")
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: TiffImagePlugin.TiffImageFile(invalid_file)) lambda: TiffImagePlugin.TiffImageFile(invalid_file))
TiffImagePlugin.PREFIXES.pop() TiffImagePlugin.PREFIXES.pop()
@ -462,12 +461,12 @@ class TestFileTiff(PillowTestCase):
# however does. # however does.
im = Image.new('RGB', (1, 1)) im = Image.new('RGB', (1, 1))
im.info['icc_profile'] = 'Dummy value' im.info['icc_profile'] = 'Dummy value'
# Try save-load round trip to make sure both handle icc_profile. # Try save-load round trip to make sure both handle icc_profile.
tmpfile = self.tempfile('temp.tif') tmpfile = self.tempfile('temp.tif')
im.save(tmpfile, 'TIFF', compression='raw') im.save(tmpfile, 'TIFF', compression='raw')
reloaded = Image.open(tmpfile) reloaded = Image.open(tmpfile)
self.assertEqual(b'Dummy value', reloaded.info['icc_profile']) self.assertEqual(b'Dummy value', reloaded.info['icc_profile'])

View File

@ -1,6 +1,7 @@
from PIL import Image, XpmImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from PIL import Image, XpmImagePlugin
# sample ppm stream # sample ppm stream
TEST_FILE = "Tests/images/hopper.xpm" TEST_FILE = "Tests/images/hopper.xpm"
@ -21,7 +22,7 @@ class TestFileXpm(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(InvalidFileType,
lambda: XpmImagePlugin.XpmImageFile(invalid_file)) lambda: XpmImagePlugin.XpmImageFile(invalid_file))
def test_load_read(self): def test_load_read(self):

View File

@ -1,6 +1,8 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import FontFile, BdfFontFile from PIL import FontFile, BdfFontFile
from PIL.exceptions import InvalidFileType
filename = "Tests/images/courB08.bdf" filename = "Tests/images/courB08.bdf"
@ -17,7 +19,7 @@ class TestFontBdf(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp: with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError, lambda: BdfFontFile.BdfFontFile(fp)) self.assertRaises(InvalidFileType, lambda: BdfFontFile.BdfFontFile(fp))
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,7 +1,7 @@
from PIL import FontFile, Image, ImageDraw, ImageFont, PcfFontFile
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image, FontFile, PcfFontFile
from PIL import ImageFont, ImageDraw
codecs = dir(Image.core) codecs = dir(Image.core)
@ -32,7 +32,7 @@ class TestFontPcf(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp: with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError, lambda: PcfFontFile.PcfFontFile(fp)) self.assertRaises(InvalidFileType, lambda: PcfFontFile.PcfFontFile(fp))
def xtest_draw(self): def xtest_draw(self):

View File

@ -1,10 +1,7 @@
from __future__ import print_function
from helper import unittest, PillowTestCase, hopper
from PIL import Image
import colorsys import colorsys
import itertools import itertools
from PIL import Image
from helper import unittest, PillowTestCase, hopper
class TestFormatHSV(PillowTestCase): class TestFormatHSV(PillowTestCase):
@ -47,10 +44,6 @@ class TestFormatHSV(PillowTestCase):
img = Image.merge('RGB', (r, g, b)) img = Image.merge('RGB', (r, g, b))
# print(("%d, %d -> "% (int(1.75*px),int(.25*px))) + \
# "(%s, %s, %s)"%img.getpixel((1.75*px, .25*px)))
# print(("%d, %d -> "% (int(.75*px),int(.25*px))) + \
# "(%s, %s, %s)"%img.getpixel((.75*px, .25*px)))
return img return img
def to_xxx_colorsys(self, im, func, mode): def to_xxx_colorsys(self, im, func, mode):
@ -95,15 +88,6 @@ class TestFormatHSV(PillowTestCase):
im = src.convert('HSV') im = src.convert('HSV')
comparable = self.to_hsv_colorsys(src) comparable = self.to_hsv_colorsys(src)
# print(im.getpixel((448, 64)))
# print(comparable.getpixel((448, 64)))
# print(im.split()[0].histogram())
# print(comparable.split()[0].histogram())
# im.split()[0].show()
# comparable.split()[0].show()
self.assert_image_similar(im.split()[0], comparable.split()[0], self.assert_image_similar(im.split()[0], comparable.split()[0],
1, "Hue conversion is wrong") 1, "Hue conversion is wrong")
self.assert_image_similar(im.split()[1], comparable.split()[1], self.assert_image_similar(im.split()[1], comparable.split()[1],
@ -111,16 +95,9 @@ class TestFormatHSV(PillowTestCase):
self.assert_image_similar(im.split()[2], comparable.split()[2], self.assert_image_similar(im.split()[2], comparable.split()[2],
1, "Value conversion is wrong") 1, "Value conversion is wrong")
# print(im.getpixel((192, 64)))
comparable = src comparable = src
im = im.convert('RGB') im = im.convert('RGB')
# im.split()[0].show()
# comparable.split()[0].show()
# print(im.getpixel((192, 64)))
# print(comparable.getpixel((192, 64)))
self.assert_image_similar(im.split()[0], comparable.split()[0], self.assert_image_similar(im.split()[0], comparable.split()[0],
3, "R conversion is wrong") 3, "R conversion is wrong")
self.assert_image_similar(im.split()[1], comparable.split()[1], self.assert_image_similar(im.split()[1], comparable.split()[1],
@ -132,12 +109,6 @@ class TestFormatHSV(PillowTestCase):
im = hopper('RGB').convert('HSV') im = hopper('RGB').convert('HSV')
comparable = self.to_hsv_colorsys(hopper('RGB')) comparable = self.to_hsv_colorsys(hopper('RGB'))
# print([ord(x) for x in im.split()[0].tobytes()[:80]])
# print([ord(x) for x in comparable.split()[0].tobytes()[:80]])
# print(im.split()[0].histogram())
# print(comparable.split()[0].histogram())
self.assert_image_similar(im.split()[0], comparable.split()[0], self.assert_image_similar(im.split()[0], comparable.split()[0],
1, "Hue conversion is wrong") 1, "Hue conversion is wrong")
self.assert_image_similar(im.split()[1], comparable.split()[1], self.assert_image_similar(im.split()[1], comparable.split()[1],
@ -150,12 +121,6 @@ class TestFormatHSV(PillowTestCase):
converted = comparable.convert('RGB') converted = comparable.convert('RGB')
comparable = self.to_rgb_colorsys(comparable) comparable = self.to_rgb_colorsys(comparable)
# print(converted.split()[1].histogram())
# print(target.split()[1].histogram())
# print([ord(x) for x in target.split()[1].tobytes()[:80]])
# print([ord(x) for x in converted.split()[1].tobytes()[:80]])
self.assert_image_similar(converted.split()[0], comparable.split()[0], self.assert_image_similar(converted.split()[0], comparable.split()[0],
3, "R conversion is wrong") 3, "R conversion is wrong")
self.assert_image_similar(converted.split()[1], comparable.split()[1], self.assert_image_similar(converted.split()[1], comparable.split()[1],

View File

@ -1,6 +1,5 @@
from __future__ import print_function
from helper import unittest, PillowTestCase, hopper
from PIL import Image, ImageDraw, ImageMode from PIL import Image, ImageDraw, ImageMode
from helper import unittest, PillowTestCase, hopper
class TestImagingResampleVulnerability(PillowTestCase): class TestImagingResampleVulnerability(PillowTestCase):
@ -324,10 +323,8 @@ class CoreResamplePassesTest(PillowTestCase):
class CoreResampleCoefficientsTest(PillowTestCase): class CoreResampleCoefficientsTest(PillowTestCase):
def test_reduce(self): def test_reduce(self):
test_color = 254 test_color = 254
# print()
for size in range(400000, 400010, 2): for size in range(400000, 400010, 2):
# print(size)
i = Image.new('L', (size, 1), 0) i = Image.new('L', (size, 1), 0)
draw = ImageDraw.Draw(i) draw = ImageDraw.Draw(i)
draw.rectangle((0, 0, i.size[0] // 2 - 1, 0), test_color) draw.rectangle((0, 0, i.size[0] // 2 - 1, 0), test_color)
@ -335,7 +332,6 @@ class CoreResampleCoefficientsTest(PillowTestCase):
px = i.resize((5, i.size[1]), Image.BICUBIC).load() px = i.resize((5, i.size[1]), Image.BICUBIC).load()
if px[2, 0] != test_color // 2: if px[2, 0] != test_color // 2:
self.assertEqual(test_color // 2, px[2, 0]) self.assertEqual(test_color // 2, px[2, 0])
# print('>', size, test_color // 2, px[2, 0])
def test_nonzero_coefficients(self): def test_nonzero_coefficients(self):
# regression test for the wrong coefficients calculation # regression test for the wrong coefficients calculation

View File

@ -1,9 +1,6 @@
from __future__ import print_function from PIL import Image, ImageMath
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image
from PIL import ImageMath
def pixel(im): def pixel(im):
if hasattr(im, "im"): if hasattr(im, "im"):

View File

@ -1,9 +1,7 @@
from __future__ import print_function import locale
from PIL import Image
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image
import locale
# ref https://github.com/python-pillow/Pillow/issues/272 # ref https://github.com/python-pillow/Pillow/issues/272
# on windows, in polish locale: # on windows, in polish locale:

View File

@ -54,7 +54,6 @@ class TestNumpy(PillowTestCase):
i = Image.fromarray(a) i = Image.fromarray(a)
if list(i.split()[0].getdata()) != list(range(100)): if list(i.split()[0].getdata()) != list(range(100)):
print("data mismatch for", dtype) print("data mismatch for", dtype)
# print(dtype, list(i.getdata()))
return i return i
# Check supported 1-bit integer formats # Check supported 1-bit integer formats

View File

@ -1,11 +1,7 @@
from __future__ import print_function from fractions import Fraction
from helper import unittest, PillowTestCase, hopper
from PIL import TiffImagePlugin, Image from PIL import TiffImagePlugin, Image
from PIL.TiffImagePlugin import IFDRational from PIL.TiffImagePlugin import IFDRational
from helper import unittest, PillowTestCase, hopper
from fractions import Fraction
class Test_IFDRational(PillowTestCase): class Test_IFDRational(PillowTestCase):

View File

@ -51,6 +51,7 @@ true color.
**SpamImagePlugin.py**:: **SpamImagePlugin.py**::
from PIL import Image, ImageFile from PIL import Image, ImageFile
from PIL.exceptions import InvalidFileType, PILReadError
import string import string
class SpamImageFile(ImageFile.ImageFile): class SpamImageFile(ImageFile.ImageFile):
@ -59,11 +60,10 @@ true color.
format_description = "Spam raster image" format_description = "Spam raster image"
def _open(self): def _open(self):
# check header # check header
header = self.fp.read(128) header = self.fp.read(128)
if header[:4] != "SPAM": if header[:4] != "SPAM":
raise SyntaxError, "not a SPAM file" raise InvalidFileType("not a SPAM file")
header = string.split(header) header = string.split(header)
@ -79,7 +79,7 @@ true color.
elif bits == 24: elif bits == 24:
self.mode = "RGB" self.mode = "RGB"
else: else:
raise SyntaxError, "unknown number of bits" raise PILReadError("unknown number of bits")
# data descriptor # data descriptor
self.tile = [ self.tile = [
@ -95,7 +95,7 @@ The format handler must always set the
:py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.Image.Image.mode` :py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.Image.Image.mode`
attributes. If these are not set, the file cannot be opened. To attributes. If these are not set, the file cannot be opened. To
simplify the decoder, the calling code considers exceptions like simplify the decoder, the calling code considers exceptions like
:py:exc:`SyntaxError`, :py:exc:`KeyError`, :py:exc:`IndexError`, :py:exc:`InvalidFileType`, :py:exc:`KeyError`, :py:exc:`IndexError`,
:py:exc:`EOFError` and :py:exc:`struct.error` as a failure to identify :py:exc:`EOFError` and :py:exc:`struct.error` as a failure to identify
the file. the file.