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.
#
from __future__ import print_function
from PIL import Image
from PIL import FontFile
from PIL import Image, FontFile
from .exceptions import InvalidFileType
# --------------------------------------------------------------------
@ -89,14 +87,12 @@ def bdf_char(f):
# Font file plugin for the X11 BDF format.
class BdfFontFile(FontFile.FontFile):
def __init__(self, fp):
FontFile.FontFile.__init__(self)
s = fp.readline()
if s[:13] != b"STARTFONT 2.1":
raise SyntaxError("not a valid BDF file")
raise InvalidFileType("not a valid BDF file")
props = {}
comments = []
@ -111,20 +107,6 @@ class BdfFontFile(FontFile.FontFile):
if s.find(b"LogicalFontDescription") < 0:
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:
c = bdf_char(fp)
if not c:

View File

@ -23,9 +23,10 @@
# See the README file for information on usage and redistribution.
#
from PIL import Image, ImageFile, ImagePalette, _binary
import math
from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.7"
@ -199,7 +200,7 @@ class BmpImageFile(ImageFile.ImageFile):
head_data = self.fp.read(14)
# choke if the file does not have the required magic bytes
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)
offset = i32(head_data[10:14])
# load bitmap information (offset=raster info)

View File

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

View File

@ -16,9 +16,9 @@
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from PIL import Image, BmpImagePlugin, _binary
from .exceptions import InvalidFileType
__version__ = "0.1"
@ -49,7 +49,7 @@ class CurImageFile(BmpImagePlugin.BmpImageFile):
# check magic
s = self.fp.read(6)
if not _accept(s):
raise SyntaxError("not a CUR file")
raise InvalidFileType("not a CUR file")
# pick the largest cursor in the file
m = b""
@ -59,14 +59,6 @@ class CurImageFile(BmpImagePlugin.BmpImageFile):
m = s
elif i8(s[0]) > i8(m[0]) and i8(s[1]) > i8(m[1]):
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:
raise TypeError("No cursors were found")

View File

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

View File

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

View File

@ -10,6 +10,8 @@
#
from PIL import Image, ImageFile
from .exceptions import InvalidFileType
_handler = None
@ -41,7 +43,7 @@ class FITSStubImageFile(ImageFile.StubImageFile):
offset = self.fp.tell()
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
# include SIMPLE, BITPIX, NAXIS, etc.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,6 +26,8 @@
from PIL import Image, ImageFile, ImagePalette, \
ImageChops, ImageSequence, _binary
from .exceptions import InvalidFileType
__version__ = "0.9"
@ -63,11 +65,10 @@ class GifImageFile(ImageFile.ImageFile):
return None
def _open(self):
# Screen
s = self.fp.read(13)
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.size = i16(s[6:]), i16(s[8:])

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -27,12 +27,14 @@
# See the README file for information on usage and redistribution.
#
from PIL import Image
from PIL._util import isPath
import io
import os
import sys
import struct
from PIL import Image
from PIL._util import isPath
from .exceptions import PILReadError, NoPluginFound
MAXBLOCK = 65536
@ -100,10 +102,10 @@ class ImageFile(Image.Image):
KeyError, # unsupported mode
EOFError, # got header but not the first frame
struct.error) as v:
raise SyntaxError(v)
raise PILReadError(v)
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):
"Set draft mode"

View File

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

View File

@ -5,11 +5,10 @@
#
# Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
from __future__ import print_function
import re
from PIL import Image
from PIL import _imagingmorph
import re
LUT_SIZE = 1 << 9
@ -152,11 +151,6 @@ class LutBuilder(object):
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
for i, pattern in enumerate(patterns):
p = pattern[0].replace('.', 'X').replace('X', '[01]')

View File

@ -17,10 +17,8 @@
#
import array
from PIL import ImageColor
from PIL import GimpPaletteFile
from PIL import GimpGradientFile
from PIL import PaletteFile
from PIL import GimpPaletteFile, GimpGradientFile, ImageColor, PaletteFile
from .exceptions import PILReadError
class ImagePalette(object):
@ -198,7 +196,6 @@ def load(filename):
# FIXME: supports GIMP gradients only
with open(filename, "rb") as fp:
for paletteHandler in [
GimpPaletteFile.GimpPaletteFile,
GimpGradientFile.GimpGradientFile,
@ -209,11 +206,9 @@ def load(filename):
lut = paletteHandler(fp).getpalette()
if lut:
break
except (SyntaxError, ValueError):
# import traceback
# traceback.print_exc()
except (PILReadError, ValueError):
pass
else:
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.
#
from __future__ import print_function
from PIL import Image
import os
import sys

View File

@ -14,10 +14,10 @@
# See the README file for information on usage and redistribution.
#
import re
from PIL import Image, ImageFile
from .exceptions import InvalidFileType
__version__ = "0.2"
@ -37,12 +37,11 @@ class ImtImageFile(ImageFile.ImageFile):
format_description = "IM Tools"
def _open(self):
# Quick rejection: if there's not a LF among the first
# 100 bytes, this is (probably) not a text header.
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)
xsize = ysize = 0

View File

@ -15,11 +15,11 @@
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from PIL import Image, ImageFile, _binary
import os
import tempfile
from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType
__version__ = "0.3"
@ -43,12 +43,6 @@ def i(c):
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
# from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
@ -72,7 +66,7 @@ class IptcImageFile(ImageFile.ImageFile):
# syntax
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
size = i8(s[3])
@ -107,8 +101,6 @@ class IptcImageFile(ImageFile.ImageFile):
else:
self.info[tag] = tagdata
# print(tag, self.info[tag])
# mode
layers = i8(self.info[(3, 60)][0])
component = i8(self.info[(3, 60)][1])

View File

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

View File

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

View File

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

View File

@ -16,10 +16,10 @@
# See the README file for information on usage and redistribution.
#
from PIL import Image, TiffImagePlugin
import olefile
from PIL import Image, TiffImagePlugin
from .exceptions import InvalidFileType, PILReadError
__version__ = "0.1"
@ -48,7 +48,7 @@ class MicImageFile(TiffImagePlugin.TiffImageFile):
try:
self.ole = olefile.OleFileIO(self.fp)
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
# 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
# an MIC file.
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.frame = 0

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -14,12 +14,6 @@
# 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
#
@ -33,12 +27,11 @@
# http://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
#
from __future__ import print_function
from PIL import Image, ImageFile
import os
import struct
import sys
from .exceptions import InvalidFileType, PILReadError
def isInt(f):
@ -75,9 +68,9 @@ def isSpiderHeader(t):
labrec = int(h[13]) # no. records in file header
labbyt = int(h[22]) # total no. of bytes in header
lenbyt = int(h[23]) # record length in bytes
# print("labrec = %d, labbyt = %d, lenbyt = %d" % (labrec,labbyt,lenbyt))
if labbyt != (labrec * lenbyt):
return 0
# looks like a valid header
return labbyt
@ -112,14 +105,14 @@ class SpiderImageFile(ImageFile.ImageFile):
t = struct.unpack('<27f', f) # little-endian
hdrlen = isSpiderHeader(t)
if hdrlen == 0:
raise SyntaxError("not a valid Spider file")
raise InvalidFileType("not a valid Spider file")
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
iform = int(h[5])
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.istack = int(h[24])
@ -142,7 +135,7 @@ class SpiderImageFile(ImageFile.ImageFile):
offset = hdrlen + self.stkoffset
self.istack = 2 # So Image knows it's still a stack
else:
raise SyntaxError("inconsistent stack header values")
raise PILReadError("inconsistent stack header values")
if self.bigendian:
self.rawmode = "F;32BF"
@ -195,30 +188,6 @@ class SpiderImageFile(ImageFile.ImageFile):
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
@ -288,34 +257,3 @@ def _save_spider(im, fp, filename):
Image.register_open(SpiderImageFile.format, SpiderImageFile)
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.
#
from PIL import Image, ImageFile, ImagePalette, _binary
from .exceptions import InvalidFileType
__version__ = "0.3"
@ -56,18 +57,18 @@ class SunImageFile(ImageFile.ImageFile):
# HEAD
s = self.fp.read(32)
if i32(s) != 0x59a66a95:
raise SyntaxError("not an SUN raster file")
raise InvalidFileType("not a SUN raster file")
offset = 32
self.size = i32(s[4:8]), i32(s[8:12])
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])
palette_type = i32(s[24:28]) # 0: None, 1: RGB, 2: Raw/arbitrary
palette_length = i32(s[28:32])
if depth == 1:
self.mode, rawmode = "1", "1;I"
elif depth == 4:
@ -85,23 +86,23 @@ class SunImageFile(ImageFile.ImageFile):
else:
self.mode, rawmode = 'RGB', 'BGRX'
else:
raise SyntaxError("Unsupported Mode/Bit Depth")
raise NotImplementedError("Unsupported Mode/Bit Depth")
if palette_length:
if palette_length > 1024:
raise SyntaxError("Unsupported Color Palette Length")
raise NotImplementedError("Unsupported Color Palette Length")
if palette_type != 1:
raise SyntaxError("Unsupported Palette Type")
raise NotImplementedError("Unsupported Palette Type")
offset = offset + palette_length
self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length))
if self.mode == "L":
self.mode = "P"
rawmode = rawmode.replace('L', 'P')
# 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. The following values are typically found in the Type
@ -126,8 +127,9 @@ class SunImageFile(ImageFile.ImageFile):
elif file_type == 2:
self.tile = [("sun_rle", (0, 0)+self.size, offset, rawmode)]
else:
raise SyntaxError('Unsupported Sun Raster file type')
raise NotImplementedError('Unsupported Sun Raster file type')
#
# registry

View File

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

View File

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

View File

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

View File

@ -19,9 +19,9 @@
# http://wvware.sourceforge.net/caolan/index.html
# http://wvware.sourceforge.net/caolan/ora-wmf.html
from __future__ import print_function
from PIL import Image, ImageFile, _binary
from .exceptions import InvalidFileType
__version__ = "0.2"
@ -110,11 +110,9 @@ class WmfStubImageFile(ImageFile.StubImageFile):
self.info["dpi"] = 72
# print(self.mode, self.size, self.info)
# sanity check (standard metafile header)
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":
# enhanced metafile
@ -143,7 +141,7 @@ class WmfStubImageFile(ImageFile.StubImageFile):
self.info["dpi"] = xdpi, ydpi
else:
raise SyntaxError("Unsupported file format")
raise InvalidFileType("Not a WMF file")
self.mode = "RGB"
self.size = size

View File

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

View File

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

View File

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

View File

@ -1,8 +1,7 @@
from __future__ import print_function
import os
from PIL import Image
from helper import unittest, PillowTestCase
from PIL import Image
import os
base = os.path.join('Tests', 'images', 'bmp')
@ -22,7 +21,6 @@ class TestBmpReference(PillowTestCase):
im.load()
except Exception: # as msg:
pass
# print("Bad Image %s: %s" %(f,msg))
def test_questionable(self):
""" These shouldn't crash/dos, but it's not well defined that these
@ -47,7 +45,6 @@ class TestBmpReference(PillowTestCase):
except Exception: # as msg:
if os.path.basename(f) in supported:
raise
# print("Bad Image %s: %s" %(f,msg))
def test_good(self):
""" 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
from PIL import Image, BmpImagePlugin
from PIL.exceptions import InvalidFileType
from helper import unittest, PillowTestCase, hopper
class TestFileBmp(PillowTestCase):
@ -27,7 +27,7 @@ class TestFileBmp(PillowTestCase):
def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError,
self.assertRaises(InvalidFileType,
lambda: BmpImagePlugin.BmpImageFile(fp))
def test_save_to_bytes(self):

View File

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

View File

@ -1,6 +1,8 @@
from helper import unittest, PillowTestCase, hopper
from PIL import Image, DcxImagePlugin
from PIL.exceptions import InvalidFileType
# Created with ImageMagick: convert hopper.ppm hopper.dcx
TEST_FILE = "Tests/images/hopper.dcx"
@ -22,7 +24,7 @@ class TestFileDcx(PillowTestCase):
def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError,
self.assertRaises(InvalidFileType,
lambda: DcxImagePlugin.DcxImageFile(fp))
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 PIL import Image, EpsImagePlugin
import io
# Our two EPS test files (they are identical except for their bounding boxes)
file1 = "Tests/images/zero_bb.eps"
@ -54,7 +55,7 @@ class TestFileEps(PillowTestCase):
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
self.assertRaises(InvalidFileType,
lambda: EpsImagePlugin.EpsImageFile(invalid_file))
def test_cmyk(self):

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase
from PIL.GimpPaletteFile import GimpPaletteFile
from PIL.exceptions import InvalidFileType, PILReadError
class TestImage(PillowTestCase):
@ -10,13 +11,13 @@ class TestImage(PillowTestCase):
GimpPaletteFile(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:
self.assertRaises(SyntaxError, lambda: GimpPaletteFile(fp))
self.assertRaises(PILReadError, lambda: GimpPaletteFile(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):
# Arrange

View File

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

View File

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

View File

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

View File

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

View File

@ -39,27 +39,6 @@ class TestFileIptc(PillowTestCase):
# Assert
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__':
unittest.main()

View File

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

View File

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

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase
from PIL import MicImagePlugin
from PIL.exceptions import PILReadError, InvalidFileType
class TestFileMic(PillowTestCase):
@ -8,12 +9,12 @@ class TestFileMic(PillowTestCase):
def test_invalid_file(self):
# Test an invalid OLE file
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
self.assertRaises(InvalidFileType,
lambda: MicImagePlugin.MicImageFile(invalid_file))
# Test a valid OLE file, but not a MIC file
ole_file = "Tests/images/test-ole-file.doc"
self.assertRaises(SyntaxError,
self.assertRaises(PILReadError,
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 PIL import Image, MspImagePlugin
TEST_FILE = "Tests/images/hopper.msp"
@ -21,7 +22,7 @@ class TestFileMsp(PillowTestCase):
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
self.assertRaises(InvalidFileType,
lambda: MspImagePlugin.MspImageFile(invalid_file))
def test_open(self):

View File

@ -1,6 +1,7 @@
from helper import unittest, PillowTestCase, hopper
from PIL import Image, ImageFile, PcxImagePlugin
from PIL.exceptions import InvalidFileType
class TestFilePcx(PillowTestCase):
@ -22,7 +23,7 @@ class TestFilePcx(PillowTestCase):
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
self.assertRaises(InvalidFileType,
lambda: PcxImagePlugin.PcxImageFile(invalid_file))
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 io import BytesIO
from PIL import Image
from PIL import ImageFile
from PIL import PngImagePlugin
import zlib
codecs = dir(Image.core)
@ -84,7 +82,7 @@ class TestFilePng(PillowTestCase):
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
self.assertRaises(InvalidFileType,
lambda: PngImagePlugin.PngImageFile(invalid_file))
def test_broken(self):
@ -317,7 +315,7 @@ class TestFilePng(PillowTestCase):
im = Image.open(BytesIO(test_file))
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):
# 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
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
try:
@ -342,7 +340,7 @@ class TestFilePng(PillowTestCase):
ImageFile.LOAD_TRUNCATED_IMAGES = True
try:
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data))
self.assertRaises(PILReadError, PngImagePlugin.PngImageFile, BytesIO(image_data))
finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
from helper import unittest, PillowTestCase
from PIL import Image
from PIL.exceptions import PILWriteError
class TestFileTga(PillowTestCase):
@ -42,7 +42,7 @@ class TestFileTga(PillowTestCase):
self.assertEqual(test_im.size, (100, 100))
# 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):
test_file = "Tests/images/rgb32rle.tga"
@ -61,7 +61,7 @@ class TestFileTga(PillowTestCase):
self.assertEqual(test_im.size, (199, 199))
# 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__':

View File

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

View File

@ -1,6 +1,8 @@
from helper import unittest, PillowTestCase
from PIL import FontFile, BdfFontFile
from PIL.exceptions import InvalidFileType
filename = "Tests/images/courB08.bdf"
@ -17,7 +19,7 @@ class TestFontBdf(PillowTestCase):
def test_invalid_file(self):
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__':

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 PIL import Image, FontFile, PcfFontFile
from PIL import ImageFont, ImageDraw
codecs = dir(Image.core)
@ -32,7 +32,7 @@ class TestFontPcf(PillowTestCase):
def test_invalid_file(self):
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):

View File

@ -1,10 +1,7 @@
from __future__ import print_function
from helper import unittest, PillowTestCase, hopper
from PIL import Image
import colorsys
import itertools
from PIL import Image
from helper import unittest, PillowTestCase, hopper
class TestFormatHSV(PillowTestCase):
@ -47,10 +44,6 @@ class TestFormatHSV(PillowTestCase):
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
def to_xxx_colorsys(self, im, func, mode):
@ -95,15 +88,6 @@ class TestFormatHSV(PillowTestCase):
im = src.convert('HSV')
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],
1, "Hue conversion is wrong")
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],
1, "Value conversion is wrong")
# print(im.getpixel((192, 64)))
comparable = src
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],
3, "R conversion is wrong")
self.assert_image_similar(im.split()[1], comparable.split()[1],
@ -132,12 +109,6 @@ class TestFormatHSV(PillowTestCase):
im = hopper('RGB').convert('HSV')
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],
1, "Hue conversion is wrong")
self.assert_image_similar(im.split()[1], comparable.split()[1],
@ -150,12 +121,6 @@ class TestFormatHSV(PillowTestCase):
converted = comparable.convert('RGB')
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],
3, "R conversion is wrong")
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 helper import unittest, PillowTestCase, hopper
class TestImagingResampleVulnerability(PillowTestCase):
@ -324,10 +323,8 @@ class CoreResamplePassesTest(PillowTestCase):
class CoreResampleCoefficientsTest(PillowTestCase):
def test_reduce(self):
test_color = 254
# print()
for size in range(400000, 400010, 2):
# print(size)
i = Image.new('L', (size, 1), 0)
draw = ImageDraw.Draw(i)
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()
if px[2, 0] != test_color // 2:
self.assertEqual(test_color // 2, px[2, 0])
# print('>', size, test_color // 2, px[2, 0])
def test_nonzero_coefficients(self):
# 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 PIL import Image
from PIL import ImageMath
def pixel(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 PIL import Image
import locale
# ref https://github.com/python-pillow/Pillow/issues/272
# on windows, in polish locale:

View File

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

View File

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

View File

@ -51,6 +51,7 @@ true color.
**SpamImagePlugin.py**::
from PIL import Image, ImageFile
from PIL.exceptions import InvalidFileType, PILReadError
import string
class SpamImageFile(ImageFile.ImageFile):
@ -59,11 +60,10 @@ true color.
format_description = "Spam raster image"
def _open(self):
# check header
header = self.fp.read(128)
if header[:4] != "SPAM":
raise SyntaxError, "not a SPAM file"
raise InvalidFileType("not a SPAM file")
header = string.split(header)
@ -79,7 +79,7 @@ true color.
elif bits == 24:
self.mode = "RGB"
else:
raise SyntaxError, "unknown number of bits"
raise PILReadError("unknown number of bits")
# data descriptor
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`
attributes. If these are not set, the file cannot be opened. To
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
the file.