Format with Black

This commit is contained in:
Hugo 2019-06-13 18:54:11 +03:00
parent d08475442b
commit f87821e010
40 changed files with 940 additions and 905 deletions

View File

@ -4,23 +4,22 @@ from PIL.GimpPaletteFile import GimpPaletteFile
class TestImage(PillowTestCase): class TestImage(PillowTestCase):
def test_sanity(self): def test_sanity(self):
with open('Tests/images/test.gpl', 'rb') as fp: with open("Tests/images/test.gpl", "rb") as fp:
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, GimpPaletteFile, fp) self.assertRaises(SyntaxError, 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, GimpPaletteFile, fp) self.assertRaises(SyntaxError, 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, GimpPaletteFile, fp) self.assertRaises(ValueError, GimpPaletteFile, fp)
def test_get_palette(self): def test_get_palette(self):
# Arrange # Arrange
with open('Tests/images/custom_gimp_palette.gpl', 'rb') as fp: with open("Tests/images/custom_gimp_palette.gpl", "rb") as fp:
palette_file = GimpPaletteFile(fp) palette_file = GimpPaletteFile(fp)
# Act # Act

View File

@ -6,7 +6,6 @@ TEST_FILE = "Tests/images/WAlaska.wind.7days.grb"
class TestFileGribStub(PillowTestCase): class TestFileGribStub(PillowTestCase):
def test_open(self): def test_open(self):
# Act # Act
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
@ -23,8 +22,9 @@ class TestFileGribStub(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(
GribStubImagePlugin.GribStubImageFile, invalid_file) SyntaxError, GribStubImagePlugin.GribStubImageFile, invalid_file
)
def test_load(self): def test_load(self):
# Arrange # Arrange

View File

@ -6,7 +6,6 @@ TEST_FILE = "Tests/images/hdf5.h5"
class TestFileHdf5Stub(PillowTestCase): class TestFileHdf5Stub(PillowTestCase):
def test_open(self): def test_open(self):
# Act # Act
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
@ -23,8 +22,9 @@ class TestFileHdf5Stub(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(
Hdf5StubImagePlugin.HDF5StubImageFile, invalid_file) SyntaxError, Hdf5StubImagePlugin.HDF5StubImageFile, invalid_file
)
def test_load(self): def test_load(self):
# Arrange # Arrange
@ -42,5 +42,5 @@ class TestFileHdf5Stub(PillowTestCase):
# Act / Assert: stub cannot save without an implemented handler # Act / Assert: stub cannot save without an implemented handler
self.assertRaises(IOError, im.save, dummy_filename) self.assertRaises(IOError, im.save, dummy_filename)
self.assertRaises( self.assertRaises(
IOError, IOError, Hdf5StubImagePlugin._save, im, dummy_fp, dummy_filename
Hdf5StubImagePlugin._save, im, dummy_fp, dummy_filename) )

View File

@ -8,11 +8,10 @@ import sys
# sample icon file # sample icon file
TEST_FILE = "Tests/images/pillow.icns" TEST_FILE = "Tests/images/pillow.icns"
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version') enable_jpeg2k = hasattr(Image.core, "jp2klib_version")
class TestFileIcns(PillowTestCase): class TestFileIcns(PillowTestCase):
def test_sanity(self): def test_sanity(self):
# Loading this icon by default should result in the largest size # Loading this icon by default should result in the largest size
# (512x512@2x) being loaded # (512x512@2x) being loaded
@ -25,7 +24,7 @@ class TestFileIcns(PillowTestCase):
self.assertEqual(im.size, (1024, 1024)) self.assertEqual(im.size, (1024, 1024))
self.assertEqual(im.format, "ICNS") self.assertEqual(im.format, "ICNS")
@unittest.skipIf(sys.platform != 'darwin', "requires macOS") @unittest.skipIf(sys.platform != "darwin", "requires macOS")
def test_save(self): def test_save(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
@ -38,12 +37,12 @@ class TestFileIcns(PillowTestCase):
self.assertEqual(reread.size, (1024, 1024)) self.assertEqual(reread.size, (1024, 1024))
self.assertEqual(reread.format, "ICNS") self.assertEqual(reread.format, "ICNS")
@unittest.skipIf(sys.platform != 'darwin', "requires macOS") @unittest.skipIf(sys.platform != "darwin", "requires macOS")
def test_save_append_images(self): def test_save_append_images(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
temp_file = self.tempfile("temp.icns") temp_file = self.tempfile("temp.icns")
provided_im = Image.new('RGBA', (32, 32), (255, 0, 0, 128)) provided_im = Image.new("RGBA", (32, 32), (255, 0, 0, 128))
im.save(temp_file, append_images=[provided_im]) im.save(temp_file, append_images=[provided_im])
reread = Image.open(temp_file) reread = Image.open(temp_file)
@ -58,13 +57,13 @@ class TestFileIcns(PillowTestCase):
# Check that we can load all of the sizes, and that the final pixel # Check that we can load all of the sizes, and that the final pixel
# dimensions are as expected # dimensions are as expected
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
for w, h, r in im.info['sizes']: for w, h, r in im.info["sizes"]:
wr = w * r wr = w * r
hr = h * r hr = h * r
im2 = Image.open(TEST_FILE) im2 = Image.open(TEST_FILE)
im2.size = (w, h, r) im2.size = (w, h, r)
im2.load() im2.load()
self.assertEqual(im2.mode, 'RGBA') self.assertEqual(im2.mode, "RGBA")
self.assertEqual(im2.size, (wr, hr)) self.assertEqual(im2.size, (wr, hr))
# Check that we cannot load an incorrect size # Check that we cannot load an incorrect size
@ -74,14 +73,14 @@ class TestFileIcns(PillowTestCase):
def test_older_icon(self): def test_older_icon(self):
# This icon was made with Icon Composer rather than iconutil; it still # This icon was made with Icon Composer rather than iconutil; it still
# uses PNG rather than JP2, however (since it was made on 10.9). # uses PNG rather than JP2, however (since it was made on 10.9).
im = Image.open('Tests/images/pillow2.icns') im = Image.open("Tests/images/pillow2.icns")
for w, h, r in im.info['sizes']: for w, h, r in im.info["sizes"]:
wr = w * r wr = w * r
hr = h * r hr = h * r
im2 = Image.open('Tests/images/pillow2.icns') im2 = Image.open("Tests/images/pillow2.icns")
im2.size = (w, h, r) im2.size = (w, h, r)
im2.load() im2.load()
self.assertEqual(im2.mode, 'RGBA') self.assertEqual(im2.mode, "RGBA")
self.assertEqual(im2.size, (wr, hr)) self.assertEqual(im2.size, (wr, hr))
def test_jp2_icon(self): def test_jp2_icon(self):
@ -95,18 +94,18 @@ class TestFileIcns(PillowTestCase):
if not enable_jpeg2k: if not enable_jpeg2k:
return return
im = Image.open('Tests/images/pillow3.icns') im = Image.open("Tests/images/pillow3.icns")
for w, h, r in im.info['sizes']: for w, h, r in im.info["sizes"]:
wr = w * r wr = w * r
hr = h * r hr = h * r
im2 = Image.open('Tests/images/pillow3.icns') im2 = Image.open("Tests/images/pillow3.icns")
im2.size = (w, h, r) im2.size = (w, h, r)
im2.load() im2.load()
self.assertEqual(im2.mode, 'RGBA') self.assertEqual(im2.mode, "RGBA")
self.assertEqual(im2.size, (wr, hr)) self.assertEqual(im2.size, (wr, hr))
def test_getimage(self): def test_getimage(self):
with open(TEST_FILE, 'rb') as fp: with open(TEST_FILE, "rb") as fp:
icns_file = IcnsImagePlugin.IcnsFile(fp) icns_file = IcnsImagePlugin.IcnsFile(fp)
im = icns_file.getimage() im = icns_file.getimage()
@ -118,6 +117,5 @@ class TestFileIcns(PillowTestCase):
self.assertEqual(im.size, (512, 512)) self.assertEqual(im.size, (512, 512))
def test_not_an_icns_file(self): def test_not_an_icns_file(self):
with io.BytesIO(b'invalid\n') as fp: with io.BytesIO(b"invalid\n") as fp:
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError, IcnsImagePlugin.IcnsFile, fp)
IcnsImagePlugin.IcnsFile, fp)

View File

@ -7,7 +7,6 @@ TEST_ICO_FILE = "Tests/images/hopper.ico"
class TestFileIco(PillowTestCase): class TestFileIco(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(TEST_ICO_FILE) im = Image.open(TEST_ICO_FILE)
im.load() im.load()
@ -18,8 +17,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(SyntaxError, IcoImagePlugin.IcoImageFile, fp)
IcoImagePlugin.IcoImageFile, fp)
def test_save_to_bytes(self): def test_save_to_bytes(self):
output = io.BytesIO() output = io.BytesIO()
@ -29,13 +27,12 @@ class TestFileIco(PillowTestCase):
# the default image # the default image
output.seek(0) output.seek(0)
reloaded = Image.open(output) reloaded = Image.open(output)
self.assertEqual(reloaded.info['sizes'], {(32, 32), (64, 64)}) self.assertEqual(reloaded.info["sizes"], {(32, 32), (64, 64)})
self.assertEqual(im.mode, reloaded.mode) self.assertEqual(im.mode, reloaded.mode)
self.assertEqual((64, 64), reloaded.size) self.assertEqual((64, 64), reloaded.size)
self.assertEqual(reloaded.format, "ICO") self.assertEqual(reloaded.format, "ICO")
self.assert_image_equal(reloaded, self.assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS))
hopper().resize((64, 64), Image.LANCZOS))
# the other one # the other one
output.seek(0) output.seek(0)
@ -45,8 +42,7 @@ class TestFileIco(PillowTestCase):
self.assertEqual(im.mode, reloaded.mode) self.assertEqual(im.mode, reloaded.mode)
self.assertEqual((32, 32), reloaded.size) self.assertEqual((32, 32), reloaded.size)
self.assertEqual(reloaded.format, "ICO") self.assertEqual(reloaded.format, "ICO")
self.assert_image_equal(reloaded, self.assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))
hopper().resize((32, 32), Image.LANCZOS))
def test_incorrect_size(self): def test_incorrect_size(self):
im = Image.open(TEST_ICO_FILE) im = Image.open(TEST_ICO_FILE)
@ -81,12 +77,13 @@ class TestFileIco(PillowTestCase):
# Assert # Assert
self.assertEqual( self.assertEqual(
im_saved.info['sizes'], im_saved.info["sizes"], {(16, 16), (24, 24), (32, 32), (48, 48)}
{(16, 16), (24, 24), (32, 32), (48, 48)}) )
def test_unexpected_size(self): def test_unexpected_size(self):
# This image has been manually hexedited to state that it is 16x32 # This image has been manually hexedited to state that it is 16x32
# while the image within is still 16x16 # while the image within is still 16x16
im = self.assert_warning(UserWarning, im = self.assert_warning(
Image.open, "Tests/images/hopper_unexpected.ico") UserWarning, Image.open, "Tests/images/hopper_unexpected.ico"
)
self.assertEqual(im.size, (16, 16)) self.assertEqual(im.size, (16, 16))

View File

@ -7,7 +7,6 @@ TEST_IM = "Tests/images/hopper.im"
class TestFileIm(PillowTestCase): class TestFileIm(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(TEST_IM) im = Image.open(TEST_IM)
im.load() im.load()
@ -19,6 +18,7 @@ class TestFileIm(PillowTestCase):
def open(): def open():
im = Image.open(TEST_IM) im = Image.open(TEST_IM)
im.load() im.load()
self.assert_warning(None, open) self.assert_warning(None, open)
def test_tell(self): def test_tell(self):
@ -45,11 +45,11 @@ class TestFileIm(PillowTestCase):
self.assertLess(im.tell(), n_frames) self.assertLess(im.tell(), n_frames)
# Test that seeking to the last frame does not raise an error # Test that seeking to the last frame does not raise an error
im.seek(n_frames-1) im.seek(n_frames - 1)
def test_roundtrip(self): def test_roundtrip(self):
for mode in ["RGB", "P", "PA"]: for mode in ["RGB", "P", "PA"]:
out = self.tempfile('temp.im') out = self.tempfile("temp.im")
im = hopper(mode) im = hopper(mode)
im.save(out) im.save(out)
reread = Image.open(out) reread = Image.open(out)
@ -57,15 +57,14 @@ class TestFileIm(PillowTestCase):
self.assert_image_equal(reread, im) self.assert_image_equal(reread, im)
def test_save_unsupported_mode(self): def test_save_unsupported_mode(self):
out = self.tempfile('temp.im') out = self.tempfile("temp.im")
im = hopper("HSV") im = hopper("HSV")
self.assertRaises(ValueError, im.save, out) self.assertRaises(ValueError, im.save, out)
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(SyntaxError, ImImagePlugin.ImImageFile, invalid_file)
ImImagePlugin.ImImageFile, invalid_file)
def test_number(self): def test_number(self):
self.assertEqual(1.2, ImImagePlugin.number("1.2")) self.assertEqual(1.2, ImImagePlugin.number("1.2"))

View File

@ -6,7 +6,6 @@ TEST_FILE = "Tests/images/iptc.jpg"
class TestFileIptc(PillowTestCase): class TestFileIptc(PillowTestCase):
def test_getiptcinfo_jpg_none(self): def test_getiptcinfo_jpg_none(self):
# Arrange # Arrange
im = hopper() im = hopper()
@ -58,6 +57,7 @@ class TestFileIptc(PillowTestCase):
except ImportError: except ImportError:
from io import StringIO from io import StringIO
import sys import sys
old_stdout = sys.stdout old_stdout = sys.stdout
sys.stdout = mystdout = StringIO() sys.stdout = mystdout = StringIO()

View File

@ -15,7 +15,6 @@ TEST_FILE = "Tests/images/hopper.jpg"
class TestFileJpeg(PillowTestCase): class TestFileJpeg(PillowTestCase):
def setUp(self): def setUp(self):
if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs: if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:
self.skipTest("jpeg support not available") self.skipTest("jpeg support not available")
@ -29,14 +28,13 @@ class TestFileJpeg(PillowTestCase):
im.bytes = test_bytes # for testing only im.bytes = test_bytes # for testing only
return im return im
def gen_random_image(self, size, mode='RGB'): def gen_random_image(self, size, mode="RGB"):
""" Generates a very hard to compress file """ Generates a very hard to compress file
:param size: tuple :param size: tuple
:param mode: optional image mode :param mode: optional image mode
""" """
return Image.frombytes(mode, size, return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))
os.urandom(size[0]*size[1]*len(mode)))
def test_sanity(self): def test_sanity(self):
@ -54,10 +52,11 @@ class TestFileJpeg(PillowTestCase):
# Test APP/COM reader (@PIL135) # Test APP/COM reader (@PIL135)
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
self.assertEqual( self.assertEqual(
im.applist[0], im.applist[0], ("APP0", b"JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00")
("APP0", b"JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00")) )
self.assertEqual(im.applist[1], ( self.assertEqual(
"COM", b"File written by Adobe Photoshop\xa8 4.0\x00")) im.applist[1], ("COM", b"File written by Adobe Photoshop\xa8 4.0\x00")
)
self.assertEqual(len(im.applist), 2) self.assertEqual(len(im.applist), 2)
def test_cmyk(self): def test_cmyk(self):
@ -72,8 +71,7 @@ class TestFileJpeg(PillowTestCase):
self.assertGreater(y, 0.8) self.assertGreater(y, 0.8)
self.assertEqual(k, 0.0) self.assertEqual(k, 0.0)
# the opposite corner is black # the opposite corner is black
c, m, y, k = [x / 255.0 for x in im.getpixel(( c, m, y, k = [x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))]
im.size[0]-1, im.size[1]-1))]
self.assertGreater(k, 0.9) self.assertGreater(k, 0.9)
# roundtrip, and check again # roundtrip, and check again
im = self.roundtrip(im) im = self.roundtrip(im)
@ -82,8 +80,7 @@ class TestFileJpeg(PillowTestCase):
self.assertGreater(m, 0.8) self.assertGreater(m, 0.8)
self.assertGreater(y, 0.8) self.assertGreater(y, 0.8)
self.assertEqual(k, 0.0) self.assertEqual(k, 0.0)
c, m, y, k = [x / 255.0 for x in im.getpixel(( c, m, y, k = [x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))]
im.size[0]-1, im.size[1]-1))]
self.assertGreater(k, 0.9) self.assertGreater(k, 0.9)
def test_dpi(self): def test_dpi(self):
@ -91,6 +88,7 @@ class TestFileJpeg(PillowTestCase):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi)) im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))
return im.info.get("dpi") return im.info.get("dpi")
self.assertEqual(test(72), (72, 72)) self.assertEqual(test(72), (72, 72))
self.assertEqual(test(300), (300, 300)) self.assertEqual(test(300), (300, 300))
self.assertEqual(test(100, 200), (100, 200)) self.assertEqual(test(100, 200), (100, 200))
@ -119,31 +117,38 @@ class TestFileJpeg(PillowTestCase):
# The ICC APP marker can store 65519 bytes per marker, so # The ICC APP marker can store 65519 bytes per marker, so
# using a 4-byte test code should allow us to detect out of # using a 4-byte test code should allow us to detect out of
# order issues. # order issues.
icc_profile = (b"Test"*int(n/4+1))[:n] icc_profile = (b"Test" * int(n / 4 + 1))[:n]
self.assertEqual(len(icc_profile), n) # sanity self.assertEqual(len(icc_profile), n) # sanity
im1 = self.roundtrip(hopper(), icc_profile=icc_profile) im1 = self.roundtrip(hopper(), icc_profile=icc_profile)
self.assertEqual(im1.info.get("icc_profile"), icc_profile or None) self.assertEqual(im1.info.get("icc_profile"), icc_profile or None)
test(0) test(0)
test(1) test(1)
test(3) test(3)
test(4) test(4)
test(5) test(5)
test(65533-14) # full JPEG marker block test(65533 - 14) # full JPEG marker block
test(65533-14+1) # full block plus one byte test(65533 - 14 + 1) # full block plus one byte
test(ImageFile.MAXBLOCK) # full buffer block test(ImageFile.MAXBLOCK) # full buffer block
test(ImageFile.MAXBLOCK+1) # full buffer block plus one byte test(ImageFile.MAXBLOCK + 1) # full buffer block plus one byte
test(ImageFile.MAXBLOCK*4+3) # large block test(ImageFile.MAXBLOCK * 4 + 3) # large block
def test_large_icc_meta(self): def test_large_icc_meta(self):
# https://github.com/python-pillow/Pillow/issues/148 # https://github.com/python-pillow/Pillow/issues/148
# Sometimes the meta data on the icc_profile block is bigger than # Sometimes the meta data on the icc_profile block is bigger than
# Image.MAXBLOCK or the image size. # Image.MAXBLOCK or the image size.
im = Image.open('Tests/images/icc_profile_big.jpg') im = Image.open("Tests/images/icc_profile_big.jpg")
f = self.tempfile("temp.jpg") f = self.tempfile("temp.jpg")
icc_profile = im.info["icc_profile"] icc_profile = im.info["icc_profile"]
# Should not raise IOError for image with icc larger than image size. # Should not raise IOError for image with icc larger than image size.
im.save(f, format='JPEG', progressive=True, quality=95, im.save(
icc_profile=icc_profile, optimize=True) f,
format="JPEG",
progressive=True,
quality=95,
icc_profile=icc_profile,
optimize=True,
)
def test_optimize(self): def test_optimize(self):
im1 = self.roundtrip(hopper()) im1 = self.roundtrip(hopper())
@ -156,9 +161,9 @@ class TestFileJpeg(PillowTestCase):
def test_optimize_large_buffer(self): def test_optimize_large_buffer(self):
# https://github.com/python-pillow/Pillow/issues/148 # https://github.com/python-pillow/Pillow/issues/148
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
# this requires ~ 1.5x Image.MAXBLOCK # this requires ~ 1.5x Image.MAXBLOCK
im = Image.new("RGB", (4096, 4096), 0xff3333) im = Image.new("RGB", (4096, 4096), 0xFF3333)
im.save(f, format="JPEG", optimize=True) im.save(f, format="JPEG", optimize=True)
def test_progressive(self): def test_progressive(self):
@ -173,13 +178,13 @@ class TestFileJpeg(PillowTestCase):
self.assertGreaterEqual(im1.bytes, im3.bytes) self.assertGreaterEqual(im1.bytes, im3.bytes)
def test_progressive_large_buffer(self): def test_progressive_large_buffer(self):
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
# this requires ~ 1.5x Image.MAXBLOCK # this requires ~ 1.5x Image.MAXBLOCK
im = Image.new("RGB", (4096, 4096), 0xff3333) im = Image.new("RGB", (4096, 4096), 0xFF3333)
im.save(f, format="JPEG", progressive=True) im.save(f, format="JPEG", progressive=True)
def test_progressive_large_buffer_highest_quality(self): def test_progressive_large_buffer_highest_quality(self):
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
im = self.gen_random_image((255, 255)) im = self.gen_random_image((255, 255))
# this requires more bytes than pixels in the image # this requires more bytes than pixels in the image
im.save(f, format="JPEG", progressive=True, quality=100) im.save(f, format="JPEG", progressive=True, quality=100)
@ -187,30 +192,31 @@ class TestFileJpeg(PillowTestCase):
def test_progressive_cmyk_buffer(self): def test_progressive_cmyk_buffer(self):
# Issue 2272, quality 90 cmyk image is tripping the large buffer bug. # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.
f = BytesIO() f = BytesIO()
im = self.gen_random_image((256, 256), 'CMYK') im = self.gen_random_image((256, 256), "CMYK")
im.save(f, format='JPEG', progressive=True, quality=94) im.save(f, format="JPEG", progressive=True, quality=94)
def test_large_exif(self): def test_large_exif(self):
# https://github.com/python-pillow/Pillow/issues/148 # https://github.com/python-pillow/Pillow/issues/148
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
im = hopper() im = hopper()
im.save(f, 'JPEG', quality=90, exif=b"1"*65532) im.save(f, "JPEG", quality=90, exif=b"1" * 65532)
def test_exif_typeerror(self): def test_exif_typeerror(self):
im = Image.open('Tests/images/exif_typeerror.jpg') im = Image.open("Tests/images/exif_typeerror.jpg")
# Should not raise a TypeError # Should not raise a TypeError
im._getexif() im._getexif()
def test_exif_gps(self): def test_exif_gps(self):
# Arrange # Arrange
im = Image.open('Tests/images/exif_gps.jpg') im = Image.open("Tests/images/exif_gps.jpg")
gps_index = 34853 gps_index = 34853
expected_exif_gps = { expected_exif_gps = {
0: b'\x00\x00\x00\x01', 0: b"\x00\x00\x00\x01",
2: (4294967295, 1), 2: (4294967295, 1),
5: b'\x01', 5: b"\x01",
30: 65535, 30: 65535,
29: '1999:99:99 99:99:99'} 29: "1999:99:99 99:99:99",
}
# Act # Act
exif = im._getexif() exif = im._getexif()
@ -222,35 +228,39 @@ class TestFileJpeg(PillowTestCase):
# rolling back exif support in 3.1 to pre-3.0 formatting. # rolling back exif support in 3.1 to pre-3.0 formatting.
# expected from 2.9, with b/u qualifiers switched for 3.2 compatibility # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility
# this test passes on 2.9 and 3.1, but not 3.0 # this test passes on 2.9 and 3.1, but not 3.0
expected_exif = {34867: 4294967295, expected_exif = {
258: (24, 24, 24), 34867: 4294967295,
36867: '2099:09:29 10:10:10', 258: (24, 24, 24),
34853: {0: b'\x00\x00\x00\x01', 36867: "2099:09:29 10:10:10",
2: (4294967295, 1), 34853: {
5: b'\x01', 0: b"\x00\x00\x00\x01",
30: 65535, 2: (4294967295, 1),
29: '1999:99:99 99:99:99'}, 5: b"\x01",
296: 65535, 30: 65535,
34665: 185, 29: "1999:99:99 99:99:99",
41994: 65535, },
514: 4294967295, 296: 65535,
271: 'Make', 34665: 185,
272: 'XXX-XXX', 41994: 65535,
305: 'PIL', 514: 4294967295,
42034: ((1, 1), (1, 1), (1, 1), (1, 1)), 271: "Make",
42035: 'LensMake', 272: "XXX-XXX",
34856: b'\xaa\xaa\xaa\xaa\xaa\xaa', 305: "PIL",
282: (4294967295, 1), 42034: ((1, 1), (1, 1), (1, 1), (1, 1)),
33434: (4294967295, 1)} 42035: "LensMake",
34856: b"\xaa\xaa\xaa\xaa\xaa\xaa",
282: (4294967295, 1),
33434: (4294967295, 1),
}
im = Image.open('Tests/images/exif_gps.jpg') im = Image.open("Tests/images/exif_gps.jpg")
exif = im._getexif() exif = im._getexif()
for tag, value in expected_exif.items(): for tag, value in expected_exif.items():
self.assertEqual(value, exif[tag]) self.assertEqual(value, exif[tag])
def test_exif_gps_typeerror(self): def test_exif_gps_typeerror(self):
im = Image.open('Tests/images/exif_gps_typeerror.jpg') im = Image.open("Tests/images/exif_gps_typeerror.jpg")
# Should not raise a TypeError # Should not raise a TypeError
im._getexif() im._getexif()
@ -291,6 +301,7 @@ class TestFileJpeg(PillowTestCase):
def getsampling(im): def getsampling(im):
layer = im.layer layer = im.layer
return layer[0][1:3] + layer[1][1:3] + layer[2][1:3] return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]
# experimental API # experimental API
im = self.roundtrip(hopper(), subsampling=-1) # default im = self.roundtrip(hopper(), subsampling=-1) # default
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
@ -312,13 +323,12 @@ class TestFileJpeg(PillowTestCase):
im = self.roundtrip(hopper(), subsampling="4:1:1") im = self.roundtrip(hopper(), subsampling="4:1:1")
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
self.assertRaises( self.assertRaises(TypeError, self.roundtrip, hopper(), subsampling="1:1:1")
TypeError, self.roundtrip, hopper(), subsampling="1:1:1")
def test_exif(self): def test_exif(self):
im = Image.open("Tests/images/pil_sample_rgb.jpg") im = Image.open("Tests/images/pil_sample_rgb.jpg")
info = im._getexif() info = im._getexif()
self.assertEqual(info[305], 'Adobe Photoshop CS Macintosh') self.assertEqual(info[305], "Adobe Photoshop CS Macintosh")
def test_mp(self): def test_mp(self):
im = Image.open("Tests/images/pil_sample_rgb.jpg") im = Image.open("Tests/images/pil_sample_rgb.jpg")
@ -327,16 +337,16 @@ class TestFileJpeg(PillowTestCase):
def test_quality_keep(self): def test_quality_keep(self):
# RGB # RGB
im = Image.open("Tests/images/hopper.jpg") im = Image.open("Tests/images/hopper.jpg")
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
im.save(f, quality='keep') im.save(f, quality="keep")
# Grayscale # Grayscale
im = Image.open("Tests/images/hopper_gray.jpg") im = Image.open("Tests/images/hopper_gray.jpg")
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
im.save(f, quality='keep') im.save(f, quality="keep")
# CMYK # CMYK
im = Image.open("Tests/images/pil_sample_cmyk.jpg") im = Image.open("Tests/images/pil_sample_cmyk.jpg")
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
im.save(f, quality='keep') im.save(f, quality="keep")
def test_junk_jpeg_header(self): def test_junk_jpeg_header(self):
# https://github.com/python-pillow/Pillow/issues/630 # https://github.com/python-pillow/Pillow/issues/630
@ -364,8 +374,8 @@ class TestFileJpeg(PillowTestCase):
def _n_qtables_helper(self, n, test_file): def _n_qtables_helper(self, n, test_file):
im = Image.open(test_file) im = Image.open(test_file)
f = self.tempfile('temp.jpg') f = self.tempfile("temp.jpg")
im.save(f, qtables=[[n]*64]*n) im.save(f, qtables=[[n] * 64] * n)
im = Image.open(f) im = Image.open(f)
self.assertEqual(len(im.quantization), n) self.assertEqual(len(im.quantization), n)
reloaded = self.roundtrip(im, qtables="keep") reloaded = self.roundtrip(im, qtables="keep")
@ -376,18 +386,18 @@ class TestFileJpeg(PillowTestCase):
qtables = im.quantization qtables = im.quantization
reloaded = self.roundtrip(im, qtables=qtables, subsampling=0) reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)
self.assertEqual(im.quantization, reloaded.quantization) self.assertEqual(im.quantization, reloaded.quantization)
self.assert_image_similar(im, self.roundtrip(im, qtables='web_low'), self.assert_image_similar(im, self.roundtrip(im, qtables="web_low"), 30)
30) self.assert_image_similar(im, self.roundtrip(im, qtables="web_high"), 30)
self.assert_image_similar(im, self.roundtrip(im, qtables='web_high'), self.assert_image_similar(im, self.roundtrip(im, qtables="keep"), 30)
30)
self.assert_image_similar(im, self.roundtrip(im, qtables='keep'), 30)
# valid bounds for baseline qtable # valid bounds for baseline qtable
bounds_qtable = [int(s) for s in ("255 1 " * 32).split(None)] bounds_qtable = [int(s) for s in ("255 1 " * 32).split(None)]
self.roundtrip(im, qtables=[bounds_qtable]) self.roundtrip(im, qtables=[bounds_qtable])
# values from wizard.txt in jpeg9-a src package. # values from wizard.txt in jpeg9-a src package.
standard_l_qtable = [int(s) for s in """ standard_l_qtable = [
int(s)
for s in """
16 11 10 16 24 40 51 61 16 11 10 16 24 40 51 61
12 12 14 19 26 58 60 55 12 12 14 19 26 58 60 55
14 13 16 24 40 57 69 56 14 13 16 24 40 57 69 56
@ -396,9 +406,14 @@ class TestFileJpeg(PillowTestCase):
24 35 55 64 81 104 113 92 24 35 55 64 81 104 113 92
49 64 78 87 103 121 120 101 49 64 78 87 103 121 120 101
72 92 95 98 112 100 103 99 72 92 95 98 112 100 103 99
""".split(None)] """.split(
None
)
]
standard_chrominance_qtable = [int(s) for s in """ standard_chrominance_qtable = [
int(s)
for s in """
17 18 24 47 99 99 99 99 17 18 24 47 99 99 99 99
18 21 26 66 99 99 99 99 18 21 26 66 99 99 99 99
24 26 56 99 99 99 99 99 24 26 56 99 99 99 99 99
@ -407,25 +422,36 @@ class TestFileJpeg(PillowTestCase):
99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99
99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99
99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99
""".split(None)] """.split(
None
)
]
# list of qtable lists # list of qtable lists
self.assert_image_similar( self.assert_image_similar(
im, self.roundtrip( im,
im, qtables=[standard_l_qtable, standard_chrominance_qtable]), self.roundtrip(
30) im, qtables=[standard_l_qtable, standard_chrominance_qtable]
),
30,
)
# tuple of qtable lists # tuple of qtable lists
self.assert_image_similar( self.assert_image_similar(
im, self.roundtrip( im,
im, qtables=(standard_l_qtable, standard_chrominance_qtable)), self.roundtrip(
30) im, qtables=(standard_l_qtable, standard_chrominance_qtable)
),
30,
)
# dict of qtable lists # dict of qtable lists
self.assert_image_similar(im, self.assert_image_similar(
self.roundtrip(im, qtables={ im,
0: standard_l_qtable, self.roundtrip(
1: standard_chrominance_qtable im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}
}), 30) ),
30,
)
self._n_qtables_helper(1, "Tests/images/hopper_gray.jpg") self._n_qtables_helper(1, "Tests/images/hopper_gray.jpg")
self._n_qtables_helper(1, "Tests/images/pil_sample_rgb.jpg") self._n_qtables_helper(1, "Tests/images/pil_sample_rgb.jpg")
@ -437,18 +463,16 @@ class TestFileJpeg(PillowTestCase):
self._n_qtables_helper(4, "Tests/images/pil_sample_cmyk.jpg") self._n_qtables_helper(4, "Tests/images/pil_sample_cmyk.jpg")
# not a sequence # not a sequence
self.assertRaises(ValueError, self.roundtrip, im, qtables='a') self.assertRaises(ValueError, self.roundtrip, im, qtables="a")
# sequence wrong length # sequence wrong length
self.assertRaises(ValueError, self.roundtrip, im, qtables=[]) self.assertRaises(ValueError, self.roundtrip, im, qtables=[])
# sequence wrong length # sequence wrong length
self.assertRaises(ValueError, self.assertRaises(ValueError, self.roundtrip, im, qtables=[1, 2, 3, 4, 5])
self.roundtrip, im, qtables=[1, 2, 3, 4, 5])
# qtable entry not a sequence # qtable entry not a sequence
self.assertRaises(ValueError, self.roundtrip, im, qtables=[1]) self.assertRaises(ValueError, self.roundtrip, im, qtables=[1])
# qtable entry has wrong number of items # qtable entry has wrong number of items
self.assertRaises(ValueError, self.assertRaises(ValueError, self.roundtrip, im, qtables=[[1, 2, 3, 4]])
self.roundtrip, im, qtables=[[1, 2, 3, 4]])
@unittest.skipUnless(djpeg_available(), "djpeg not available") @unittest.skipUnless(djpeg_available(), "djpeg not available")
def test_load_djpeg(self): def test_load_djpeg(self):
@ -468,11 +492,12 @@ class TestFileJpeg(PillowTestCase):
def test_no_duplicate_0x1001_tag(self): def test_no_duplicate_0x1001_tag(self):
# Arrange # Arrange
from PIL import ExifTags from PIL import ExifTags
tag_ids = {v: k for k, v in ExifTags.TAGS.items()} tag_ids = {v: k for k, v in ExifTags.TAGS.items()}
# Assert # Assert
self.assertEqual(tag_ids['RelatedImageWidth'], 0x1001) self.assertEqual(tag_ids["RelatedImageWidth"], 0x1001)
self.assertEqual(tag_ids['RelatedImageLength'], 0x1002) self.assertEqual(tag_ids["RelatedImageLength"], 0x1002)
def test_MAXBLOCK_scaling(self): def test_MAXBLOCK_scaling(self):
im = self.gen_random_image((512, 512)) im = self.gen_random_image((512, 512))
@ -482,9 +507,9 @@ class TestFileJpeg(PillowTestCase):
reloaded = Image.open(f) reloaded = Image.open(f)
# none of these should crash # none of these should crash
reloaded.save(f, quality='keep') reloaded.save(f, quality="keep")
reloaded.save(f, quality='keep', progressive=True) reloaded.save(f, quality="keep", progressive=True)
reloaded.save(f, quality='keep', optimize=True) reloaded.save(f, quality="keep", optimize=True)
def test_bad_mpo_header(self): def test_bad_mpo_header(self):
""" Treat unknown MPO as JPEG """ """ Treat unknown MPO as JPEG """
@ -500,14 +525,14 @@ class TestFileJpeg(PillowTestCase):
def test_save_correct_modes(self): def test_save_correct_modes(self):
out = BytesIO() out = BytesIO()
for mode in ['1', 'L', 'RGB', 'RGBX', 'CMYK', 'YCbCr']: for mode in ["1", "L", "RGB", "RGBX", "CMYK", "YCbCr"]:
img = Image.new(mode, (20, 20)) img = Image.new(mode, (20, 20))
img.save(out, "JPEG") img.save(out, "JPEG")
def test_save_wrong_modes(self): def test_save_wrong_modes(self):
# ref https://github.com/python-pillow/Pillow/issues/2005 # ref https://github.com/python-pillow/Pillow/issues/2005
out = BytesIO() out = BytesIO()
for mode in ['LA', 'La', 'RGBA', 'RGBa', 'P']: for mode in ["LA", "La", "RGBA", "RGBa", "P"]:
img = Image.new(mode, (20, 20)) img = Image.new(mode, (20, 20))
self.assertRaises(IOError, img.save, out, "JPEG") self.assertRaises(IOError, img.save, out, "JPEG")
@ -517,25 +542,25 @@ class TestFileJpeg(PillowTestCase):
im = Image.open("Tests/images/hopper.tif") im = Image.open("Tests/images/hopper.tif")
# Act # Act
im.save(outfile, 'JPEG', dpi=im.info['dpi']) im.save(outfile, "JPEG", dpi=im.info["dpi"])
# Assert # Assert
reloaded = Image.open(outfile) reloaded = Image.open(outfile)
reloaded.load() reloaded.load()
self.assertEqual(im.info['dpi'], reloaded.info['dpi']) self.assertEqual(im.info["dpi"], reloaded.info["dpi"])
def test_load_dpi_rounding(self): def test_load_dpi_rounding(self):
# Round up # Round up
im = Image.open('Tests/images/iptc_roundUp.jpg') im = Image.open("Tests/images/iptc_roundUp.jpg")
self.assertEqual(im.info["dpi"], (44, 44)) self.assertEqual(im.info["dpi"], (44, 44))
# Round down # Round down
im = Image.open('Tests/images/iptc_roundDown.jpg') im = Image.open("Tests/images/iptc_roundDown.jpg")
self.assertEqual(im.info["dpi"], (2, 2)) self.assertEqual(im.info["dpi"], (2, 2))
def test_save_dpi_rounding(self): def test_save_dpi_rounding(self):
outfile = self.tempfile("temp.jpg") outfile = self.tempfile("temp.jpg")
im = Image.open('Tests/images/hopper.jpg') im = Image.open("Tests/images/hopper.jpg")
im.save(outfile, dpi=(72.2, 72.2)) im.save(outfile, dpi=(72.2, 72.2))
reloaded = Image.open(outfile) reloaded = Image.open(outfile)
@ -609,23 +634,26 @@ class TestFileJpeg(PillowTestCase):
im = Image.open("Tests/images/exif-ifd-offset.jpg") im = Image.open("Tests/images/exif-ifd-offset.jpg")
# Act / Assert # Act / Assert
self.assertEqual(im._getexif()[306], '2017:03:13 23:03:09') self.assertEqual(im._getexif()[306], "2017:03:13 23:03:09")
def test_photoshop(self): def test_photoshop(self):
im = Image.open("Tests/images/photoshop-200dpi.jpg") im = Image.open("Tests/images/photoshop-200dpi.jpg")
self.assertEqual(im.info["photoshop"][0x03ed], { self.assertEqual(
'XResolution': 200.0, im.info["photoshop"][0x03ED],
'DisplayedUnitsX': 1, {
'YResolution': 200.0, "XResolution": 200.0,
'DisplayedUnitsY': 1, "DisplayedUnitsX": 1,
}) "YResolution": 200.0,
"DisplayedUnitsY": 1,
},
)
# This image does not contain a Photoshop header string # This image does not contain a Photoshop header string
im = Image.open("Tests/images/app13.jpg") im = Image.open("Tests/images/app13.jpg")
self.assertNotIn("photoshop", im.info) self.assertNotIn("photoshop", im.info)
@unittest.skipUnless(sys.platform.startswith('win32'), "Windows only") @unittest.skipUnless(sys.platform.startswith("win32"), "Windows only")
class TestFileCloseW32(PillowTestCase): class TestFileCloseW32(PillowTestCase):
def setUp(self): def setUp(self):
if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs: if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:

View File

@ -5,7 +5,7 @@ from io import BytesIO
codecs = dir(Image.core) codecs = dir(Image.core)
test_card = Image.open('Tests/images/test-card.png') test_card = Image.open("Tests/images/test-card.png")
test_card.load() test_card.load()
# OpenJPEG 2.0.0 outputs this debugging message sometimes; we should # OpenJPEG 2.0.0 outputs this debugging message sometimes; we should
@ -14,10 +14,9 @@ test_card.load()
class TestFileJpeg2k(PillowTestCase): class TestFileJpeg2k(PillowTestCase):
def setUp(self): def setUp(self):
if "jpeg2k_encoder" not in codecs or "jpeg2k_decoder" not in codecs: if "jpeg2k_encoder" not in codecs or "jpeg2k_decoder" not in codecs:
self.skipTest('JPEG 2000 support not available') self.skipTest("JPEG 2000 support not available")
def roundtrip(self, im, **options): def roundtrip(self, im, **options):
out = BytesIO() out = BytesIO()
@ -31,29 +30,28 @@ class TestFileJpeg2k(PillowTestCase):
def test_sanity(self): def test_sanity(self):
# Internal version number # Internal version number
self.assertRegex(Image.core.jp2klib_version, r'\d+\.\d+\.\d+$') self.assertRegex(Image.core.jp2klib_version, r"\d+\.\d+\.\d+$")
im = Image.open('Tests/images/test-card-lossless.jp2') im = Image.open("Tests/images/test-card-lossless.jp2")
px = im.load() px = im.load()
self.assertEqual(px[0, 0], (0, 0, 0)) self.assertEqual(px[0, 0], (0, 0, 0))
self.assertEqual(im.mode, 'RGB') self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (640, 480)) self.assertEqual(im.size, (640, 480))
self.assertEqual(im.format, 'JPEG2000') self.assertEqual(im.format, "JPEG2000")
self.assertEqual(im.get_format_mimetype(), 'image/jp2') self.assertEqual(im.get_format_mimetype(), "image/jp2")
def test_jpf(self): def test_jpf(self):
im = Image.open('Tests/images/balloon.jpf') im = Image.open("Tests/images/balloon.jpf")
self.assertEqual(im.format, 'JPEG2000') self.assertEqual(im.format, "JPEG2000")
self.assertEqual(im.get_format_mimetype(), 'image/jpx') self.assertEqual(im.get_format_mimetype(), "image/jpx")
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(SyntaxError, Jpeg2KImagePlugin.Jpeg2KImageFile, invalid_file)
Jpeg2KImagePlugin.Jpeg2KImageFile, invalid_file)
def test_bytesio(self): def test_bytesio(self):
with open('Tests/images/test-card-lossless.jp2', 'rb') as f: with open("Tests/images/test-card-lossless.jp2", "rb") as f:
data = BytesIO(f.read()) data = BytesIO(f.read())
im = Image.open(data) im = Image.open(data)
im.load() im.load()
@ -63,14 +61,14 @@ class TestFileJpeg2k(PillowTestCase):
# PIL (they were made using Adobe Photoshop) # PIL (they were made using Adobe Photoshop)
def test_lossless(self): def test_lossless(self):
im = Image.open('Tests/images/test-card-lossless.jp2') im = Image.open("Tests/images/test-card-lossless.jp2")
im.load() im.load()
outfile = self.tempfile('temp_test-card.png') outfile = self.tempfile("temp_test-card.png")
im.save(outfile) im.save(outfile)
self.assert_image_similar(im, test_card, 1.0e-3) self.assert_image_similar(im, test_card, 1.0e-3)
def test_lossy_tiled(self): def test_lossy_tiled(self):
im = Image.open('Tests/images/test-card-lossy-tiled.jp2') im = Image.open("Tests/images/test-card-lossy-tiled.jp2")
im.load() im.load()
self.assert_image_similar(im, test_card, 2.0) self.assert_image_similar(im, test_card, 2.0)
@ -88,8 +86,8 @@ class TestFileJpeg2k(PillowTestCase):
def test_tiled_offset_rt(self): def test_tiled_offset_rt(self):
im = self.roundtrip( im = self.roundtrip(
test_card, tile_size=(128, 128), test_card, tile_size=(128, 128), tile_offset=(0, 0), offset=(32, 32)
tile_offset=(0, 0), offset=(32, 32)) )
self.assert_image_equal(im, test_card) self.assert_image_equal(im, test_card)
def test_irreversible_rt(self): def test_irreversible_rt(self):
@ -97,40 +95,34 @@ class TestFileJpeg2k(PillowTestCase):
self.assert_image_similar(im, test_card, 2.0) self.assert_image_similar(im, test_card, 2.0)
def test_prog_qual_rt(self): def test_prog_qual_rt(self):
im = self.roundtrip( im = self.roundtrip(test_card, quality_layers=[60, 40, 20], progression="LRCP")
test_card, quality_layers=[60, 40, 20], progression='LRCP')
self.assert_image_similar(im, test_card, 2.0) self.assert_image_similar(im, test_card, 2.0)
def test_prog_res_rt(self): def test_prog_res_rt(self):
im = self.roundtrip(test_card, num_resolutions=8, progression='RLCP') im = self.roundtrip(test_card, num_resolutions=8, progression="RLCP")
self.assert_image_equal(im, test_card) self.assert_image_equal(im, test_card)
def test_reduce(self): def test_reduce(self):
im = Image.open('Tests/images/test-card-lossless.jp2') im = Image.open("Tests/images/test-card-lossless.jp2")
im.reduce = 2 im.reduce = 2
im.load() im.load()
self.assertEqual(im.size, (160, 120)) self.assertEqual(im.size, (160, 120))
def test_layers_type(self): def test_layers_type(self):
outfile = self.tempfile('temp_layers.jp2') outfile = self.tempfile("temp_layers.jp2")
for quality_layers in [ for quality_layers in [[100, 50, 10], (100, 50, 10), None]:
[100, 50, 10],
(100, 50, 10),
None
]:
test_card.save(outfile, quality_layers=quality_layers) test_card.save(outfile, quality_layers=quality_layers)
for quality_layers in [ for quality_layers in ["quality_layers", ("100", "50", "10")]:
'quality_layers', self.assertRaises(
('100', '50', '10') ValueError, test_card.save, outfile, quality_layers=quality_layers
]: )
self.assertRaises(ValueError, test_card.save, outfile,
quality_layers=quality_layers)
def test_layers(self): def test_layers(self):
out = BytesIO() out = BytesIO()
test_card.save(out, 'JPEG2000', quality_layers=[100, 50, 10], test_card.save(
progression='LRCP') out, "JPEG2000", quality_layers=[100, 50, 10], progression="LRCP"
)
out.seek(0) out.seek(0)
im = Image.open(out) im = Image.open(out)
@ -146,49 +138,49 @@ class TestFileJpeg2k(PillowTestCase):
def test_rgba(self): def test_rgba(self):
# Arrange # Arrange
j2k = Image.open('Tests/images/rgb_trns_ycbc.j2k') j2k = Image.open("Tests/images/rgb_trns_ycbc.j2k")
jp2 = Image.open('Tests/images/rgb_trns_ycbc.jp2') jp2 = Image.open("Tests/images/rgb_trns_ycbc.jp2")
# Act # Act
j2k.load() j2k.load()
jp2.load() jp2.load()
# Assert # Assert
self.assertEqual(j2k.mode, 'RGBA') self.assertEqual(j2k.mode, "RGBA")
self.assertEqual(jp2.mode, 'RGBA') self.assertEqual(jp2.mode, "RGBA")
def test_16bit_monochrome_has_correct_mode(self): def test_16bit_monochrome_has_correct_mode(self):
j2k = Image.open('Tests/images/16bit.cropped.j2k') j2k = Image.open("Tests/images/16bit.cropped.j2k")
jp2 = Image.open('Tests/images/16bit.cropped.jp2') jp2 = Image.open("Tests/images/16bit.cropped.jp2")
j2k.load() j2k.load()
jp2.load() jp2.load()
self.assertEqual(j2k.mode, 'I;16') self.assertEqual(j2k.mode, "I;16")
self.assertEqual(jp2.mode, 'I;16') self.assertEqual(jp2.mode, "I;16")
def test_16bit_monochrome_jp2_like_tiff(self): def test_16bit_monochrome_jp2_like_tiff(self):
tiff_16bit = Image.open('Tests/images/16bit.cropped.tif') tiff_16bit = Image.open("Tests/images/16bit.cropped.tif")
jp2 = Image.open('Tests/images/16bit.cropped.jp2') jp2 = Image.open("Tests/images/16bit.cropped.jp2")
self.assert_image_similar(jp2, tiff_16bit, 1e-3) self.assert_image_similar(jp2, tiff_16bit, 1e-3)
def test_16bit_monochrome_j2k_like_tiff(self): def test_16bit_monochrome_j2k_like_tiff(self):
tiff_16bit = Image.open('Tests/images/16bit.cropped.tif') tiff_16bit = Image.open("Tests/images/16bit.cropped.tif")
j2k = Image.open('Tests/images/16bit.cropped.j2k') j2k = Image.open("Tests/images/16bit.cropped.j2k")
self.assert_image_similar(j2k, tiff_16bit, 1e-3) self.assert_image_similar(j2k, tiff_16bit, 1e-3)
def test_16bit_j2k_roundtrips(self): def test_16bit_j2k_roundtrips(self):
j2k = Image.open('Tests/images/16bit.cropped.j2k') j2k = Image.open("Tests/images/16bit.cropped.j2k")
im = self.roundtrip(j2k) im = self.roundtrip(j2k)
self.assert_image_equal(im, j2k) self.assert_image_equal(im, j2k)
def test_16bit_jp2_roundtrips(self): def test_16bit_jp2_roundtrips(self):
jp2 = Image.open('Tests/images/16bit.cropped.jp2') jp2 = Image.open("Tests/images/16bit.cropped.jp2")
im = self.roundtrip(jp2) im = self.roundtrip(jp2)
self.assert_image_equal(im, jp2) self.assert_image_equal(im, jp2)
@ -196,12 +188,13 @@ class TestFileJpeg2k(PillowTestCase):
# prepatch, a malformed jp2 file could cause an UnboundLocalError # prepatch, a malformed jp2 file could cause an UnboundLocalError
# exception. # exception.
with self.assertRaises(IOError): with self.assertRaises(IOError):
Image.open('Tests/images/unbound_variable.jp2') Image.open("Tests/images/unbound_variable.jp2")
def test_parser_feed(self): def test_parser_feed(self):
# Arrange # Arrange
from PIL import ImageFile from PIL import ImageFile
with open('Tests/images/test-card-lossless.jp2', 'rb') as f:
with open("Tests/images/test-card-lossless.jp2", "rb") as f:
data = f.read() data = f.read()
# Act # Act

View File

@ -16,9 +16,8 @@ logger = logging.getLogger(__name__)
class LibTiffTestCase(PillowTestCase): class LibTiffTestCase(PillowTestCase):
def setUp(self): def setUp(self):
if not features.check('libtiff'): if not features.check("libtiff"):
self.skipTest("tiff support not available") self.skipTest("tiff support not available")
def _assert_noerr(self, im): def _assert_noerr(self, im):
@ -31,7 +30,7 @@ class LibTiffTestCase(PillowTestCase):
im.getdata() im.getdata()
try: try:
self.assertEqual(im._compression, 'group4') self.assertEqual(im._compression, "group4")
except AttributeError: except AttributeError:
print("No _compression") print("No _compression")
print(dir(im)) print(dir(im))
@ -41,11 +40,10 @@ class LibTiffTestCase(PillowTestCase):
im.save(out) im.save(out)
out_bytes = io.BytesIO() out_bytes = io.BytesIO()
im.save(out_bytes, format='tiff', compression='group4') im.save(out_bytes, format="tiff", compression="group4")
class TestFileLibTiff(LibTiffTestCase): class TestFileLibTiff(LibTiffTestCase):
def test_g4_tiff(self): def test_g4_tiff(self):
"""Test the ordinary file path load path""" """Test the ordinary file path load path"""
@ -64,7 +62,7 @@ class TestFileLibTiff(LibTiffTestCase):
"""Testing the string load path""" """Testing the string load path"""
test_file = "Tests/images/hopper_g4_500.tif" test_file = "Tests/images/hopper_g4_500.tif"
with open(test_file, 'rb') as f: with open(test_file, "rb") as f:
im = Image.open(f) im = Image.open(f)
self.assertEqual(im.size, (500, 500)) self.assertEqual(im.size, (500, 500))
@ -74,7 +72,7 @@ class TestFileLibTiff(LibTiffTestCase):
"""Testing the stringio loading code path""" """Testing the stringio loading code path"""
test_file = "Tests/images/hopper_g4_500.tif" test_file = "Tests/images/hopper_g4_500.tif"
s = io.BytesIO() s = io.BytesIO()
with open(test_file, 'rb') as f: with open(test_file, "rb") as f:
s.write(f.read()) s.write(f.read())
s.seek(0) s.seek(0)
im = Image.open(s) im = Image.open(s)
@ -84,16 +82,16 @@ class TestFileLibTiff(LibTiffTestCase):
def test_g4_eq_png(self): def test_g4_eq_png(self):
""" Checking that we're actually getting the data that we expect""" """ Checking that we're actually getting the data that we expect"""
png = Image.open('Tests/images/hopper_bw_500.png') png = Image.open("Tests/images/hopper_bw_500.png")
g4 = Image.open('Tests/images/hopper_g4_500.tif') g4 = Image.open("Tests/images/hopper_g4_500.tif")
self.assert_image_equal(g4, png) self.assert_image_equal(g4, png)
# see https://github.com/python-pillow/Pillow/issues/279 # see https://github.com/python-pillow/Pillow/issues/279
def test_g4_fillorder_eq_png(self): def test_g4_fillorder_eq_png(self):
""" Checking that we're actually getting the data that we expect""" """ Checking that we're actually getting the data that we expect"""
png = Image.open('Tests/images/g4-fillorder-test.png') png = Image.open("Tests/images/g4-fillorder-test.png")
g4 = Image.open('Tests/images/g4-fillorder-test.tif') g4 = Image.open("Tests/images/g4-fillorder-test.tif")
self.assert_image_equal(g4, png) self.assert_image_equal(g4, png)
@ -111,9 +109,9 @@ class TestFileLibTiff(LibTiffTestCase):
self.assertEqual(reread.size, (500, 500)) self.assertEqual(reread.size, (500, 500))
self._assert_noerr(reread) self._assert_noerr(reread)
self.assert_image_equal(reread, rot) self.assert_image_equal(reread, rot)
self.assertEqual(reread.info['compression'], 'group4') self.assertEqual(reread.info["compression"], "group4")
self.assertEqual(reread.info['compression'], orig.info['compression']) self.assertEqual(reread.info["compression"], orig.info["compression"])
self.assertNotEqual(orig.tobytes(), reread.tobytes()) self.assertNotEqual(orig.tobytes(), reread.tobytes())
@ -123,18 +121,16 @@ class TestFileLibTiff(LibTiffTestCase):
self.assertEqual(im.mode, "RGB") self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (278, 374)) self.assertEqual(im.size, (278, 374))
self.assertEqual( self.assertEqual(im.tile[0][:3], ("tiff_adobe_deflate", (0, 0, 278, 374), 0))
im.tile[0][:3], ('tiff_adobe_deflate', (0, 0, 278, 374), 0))
im.load() im.load()
self.assert_image_equal_tofile(im, self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
'Tests/images/tiff_adobe_deflate.png')
def test_write_metadata(self): def test_write_metadata(self):
""" Test metadata writing through libtiff """ """ Test metadata writing through libtiff """
for legacy_api in [False, True]: for legacy_api in [False, True]:
img = Image.open('Tests/images/hopper_g4.tif') img = Image.open("Tests/images/hopper_g4.tif")
f = self.tempfile('temp.tiff') f = self.tempfile("temp.tiff")
img.save(f, tiffinfo=img.tag) img.save(f, tiffinfo=img.tag)
@ -145,8 +141,12 @@ class TestFileLibTiff(LibTiffTestCase):
# PhotometricInterpretation is set from SAVE_INFO, # PhotometricInterpretation is set from SAVE_INFO,
# not the original image. # not the original image.
ignored = ['StripByteCounts', 'RowsPerStrip', 'PageNumber', ignored = [
'PhotometricInterpretation'] "StripByteCounts",
"RowsPerStrip",
"PageNumber",
"PhotometricInterpretation",
]
loaded = Image.open(f) loaded = Image.open(f)
if legacy_api: if legacy_api:
@ -154,28 +154,27 @@ class TestFileLibTiff(LibTiffTestCase):
else: else:
reloaded = loaded.tag_v2.named() reloaded = loaded.tag_v2.named()
for tag, value in itertools.chain(reloaded.items(), for tag, value in itertools.chain(reloaded.items(), original.items()):
original.items()):
if tag not in ignored: if tag not in ignored:
val = original[tag] val = original[tag]
if tag.endswith('Resolution'): if tag.endswith("Resolution"):
if legacy_api: if legacy_api:
self.assertEqual( self.assertEqual(
c_float(val[0][0] / val[0][1]).value, c_float(val[0][0] / val[0][1]).value,
c_float(value[0][0] / value[0][1]).value, c_float(value[0][0] / value[0][1]).value,
msg="%s didn't roundtrip" % tag) msg="%s didn't roundtrip" % tag,
)
else: else:
self.assertEqual( self.assertEqual(
c_float(val).value, c_float(value).value, c_float(val).value,
msg="%s didn't roundtrip" % tag) c_float(value).value,
msg="%s didn't roundtrip" % tag,
)
else: else:
self.assertEqual( self.assertEqual(val, value, msg="%s didn't roundtrip" % tag)
val, value, msg="%s didn't roundtrip" % tag)
# https://github.com/python-pillow/Pillow/issues/1561 # https://github.com/python-pillow/Pillow/issues/1561
requested_fields = ['StripByteCounts', requested_fields = ["StripByteCounts", "RowsPerStrip", "StripOffsets"]
'RowsPerStrip',
'StripOffsets']
for field in requested_fields: for field in requested_fields:
self.assertIn(field, reloaded, "%s not in metadata" % field) self.assertIn(field, reloaded, "%s not in metadata" % field)
@ -186,13 +185,15 @@ class TestFileLibTiff(LibTiffTestCase):
# Get the list of the ones that we should be able to write # Get the list of the ones that we should be able to write
core_items = {tag: info for tag, info in ((s, TiffTags.lookup(s)) for s core_items = {
in TiffTags.LIBTIFF_CORE) tag: info
if info.type is not None} for tag, info in ((s, TiffTags.lookup(s)) for s in TiffTags.LIBTIFF_CORE)
if info.type is not None
}
# Exclude ones that have special meaning # Exclude ones that have special meaning
# that we're already testing them # that we're already testing them
im = Image.open('Tests/images/hopper_g4.tif') im = Image.open("Tests/images/hopper_g4.tif")
for tag in im.tag_v2: for tag in im.tag_v2:
try: try:
del core_items[tag] del core_items[tag]
@ -206,11 +207,13 @@ class TestFileLibTiff(LibTiffTestCase):
# 5: "rational", # 5: "rational",
# 12: "double", # 12: "double",
# Type: dummy value # Type: dummy value
values = {2: 'test', values = {
3: 1, 2: "test",
4: 2**20, 3: 1,
5: TiffImagePlugin.IFDRational(100, 1), 4: 2 ** 20,
12: 1.05} 5: TiffImagePlugin.IFDRational(100, 1),
12: 1.05,
}
new_ifd = TiffImagePlugin.ImageFileDirectory_v2() new_ifd = TiffImagePlugin.ImageFileDirectory_v2()
for tag, info in core_items.items(): for tag, info in core_items.items():
@ -219,8 +222,7 @@ class TestFileLibTiff(LibTiffTestCase):
if info.length == 0: if info.length == 0:
new_ifd[tag] = tuple(values[info.type] for _ in range(3)) new_ifd[tag] = tuple(values[info.type] for _ in range(3))
else: else:
new_ifd[tag] = tuple(values[info.type] new_ifd[tag] = tuple(values[info.type] for _ in range(info.length))
for _ in range(info.length))
# Extra samples really doesn't make sense in this application. # Extra samples really doesn't make sense in this application.
del new_ifd[338] del new_ifd[338]
@ -236,16 +238,17 @@ class TestFileLibTiff(LibTiffTestCase):
custom = { custom = {
37000: [4, TiffTags.SHORT], 37000: [4, TiffTags.SHORT],
37001: [4.2, TiffTags.RATIONAL], 37001: [4.2, TiffTags.RATIONAL],
37002: ['custom tag value', TiffTags.ASCII], 37002: ["custom tag value", TiffTags.ASCII],
37003: [u'custom tag value', TiffTags.ASCII], 37003: [u"custom tag value", TiffTags.ASCII],
37004: [b'custom tag value', TiffTags.BYTE] 37004: [b"custom tag value", TiffTags.BYTE],
} }
libtiff_version = TiffImagePlugin._libtiff_version() libtiff_version = TiffImagePlugin._libtiff_version()
libtiffs = [False] libtiffs = [False]
if distutils.version.StrictVersion(libtiff_version) >= \ if distutils.version.StrictVersion(
distutils.version.StrictVersion("4.0"): libtiff_version
) >= distutils.version.StrictVersion("4.0"):
libtiffs.append(True) libtiffs.append(True)
for libtiff in libtiffs: for libtiff in libtiffs:
@ -281,68 +284,68 @@ class TestFileLibTiff(LibTiffTestCase):
def test_int_dpi(self): def test_int_dpi(self):
# issue #1765 # issue #1765
im = hopper('RGB') im = hopper("RGB")
out = self.tempfile('temp.tif') out = self.tempfile("temp.tif")
TiffImagePlugin.WRITE_LIBTIFF = True TiffImagePlugin.WRITE_LIBTIFF = True
im.save(out, dpi=(72, 72)) im.save(out, dpi=(72, 72))
TiffImagePlugin.WRITE_LIBTIFF = False TiffImagePlugin.WRITE_LIBTIFF = False
reloaded = Image.open(out) reloaded = Image.open(out)
self.assertEqual(reloaded.info['dpi'], (72.0, 72.0)) self.assertEqual(reloaded.info["dpi"], (72.0, 72.0))
def test_g3_compression(self): def test_g3_compression(self):
i = Image.open('Tests/images/hopper_g4_500.tif') i = Image.open("Tests/images/hopper_g4_500.tif")
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
i.save(out, compression='group3') i.save(out, compression="group3")
reread = Image.open(out) reread = Image.open(out)
self.assertEqual(reread.info['compression'], 'group3') self.assertEqual(reread.info["compression"], "group3")
self.assert_image_equal(reread, i) self.assert_image_equal(reread, i)
def test_little_endian(self): def test_little_endian(self):
im = Image.open('Tests/images/16bit.deflate.tif') im = Image.open("Tests/images/16bit.deflate.tif")
self.assertEqual(im.getpixel((0, 0)), 480) self.assertEqual(im.getpixel((0, 0)), 480)
self.assertEqual(im.mode, 'I;16') self.assertEqual(im.mode, "I;16")
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (little endian) # Bytes are in image native order (little endian)
if py3: if py3:
self.assertEqual(b[0], ord(b'\xe0')) self.assertEqual(b[0], ord(b"\xe0"))
self.assertEqual(b[1], ord(b'\x01')) self.assertEqual(b[1], ord(b"\x01"))
else: else:
self.assertEqual(b[0], b'\xe0') self.assertEqual(b[0], b"\xe0")
self.assertEqual(b[1], b'\x01') self.assertEqual(b[1], b"\x01")
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
# out = "temp.le.tif" # out = "temp.le.tif"
im.save(out) im.save(out)
reread = Image.open(out) reread = Image.open(out)
self.assertEqual(reread.info['compression'], im.info['compression']) self.assertEqual(reread.info["compression"], im.info["compression"])
self.assertEqual(reread.getpixel((0, 0)), 480) self.assertEqual(reread.getpixel((0, 0)), 480)
# UNDONE - libtiff defaults to writing in native endian, so # UNDONE - libtiff defaults to writing in native endian, so
# on big endian, we'll get back mode = 'I;16B' here. # on big endian, we'll get back mode = 'I;16B' here.
def test_big_endian(self): def test_big_endian(self):
im = Image.open('Tests/images/16bit.MM.deflate.tif') im = Image.open("Tests/images/16bit.MM.deflate.tif")
self.assertEqual(im.getpixel((0, 0)), 480) self.assertEqual(im.getpixel((0, 0)), 480)
self.assertEqual(im.mode, 'I;16B') self.assertEqual(im.mode, "I;16B")
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (big endian) # Bytes are in image native order (big endian)
if py3: if py3:
self.assertEqual(b[0], ord(b'\x01')) self.assertEqual(b[0], ord(b"\x01"))
self.assertEqual(b[1], ord(b'\xe0')) self.assertEqual(b[1], ord(b"\xe0"))
else: else:
self.assertEqual(b[0], b'\x01') self.assertEqual(b[0], b"\x01")
self.assertEqual(b[1], b'\xe0') self.assertEqual(b[1], b"\xe0")
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
im.save(out) im.save(out)
reread = Image.open(out) reread = Image.open(out)
self.assertEqual(reread.info['compression'], im.info['compression']) self.assertEqual(reread.info["compression"], im.info["compression"])
self.assertEqual(reread.getpixel((0, 0)), 480) self.assertEqual(reread.getpixel((0, 0)), 480)
def test_g4_string_info(self): def test_g4_string_info(self):
@ -352,18 +355,18 @@ class TestFileLibTiff(LibTiffTestCase):
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
orig.tag[269] = 'temp.tif' orig.tag[269] = "temp.tif"
orig.save(out) orig.save(out)
reread = Image.open(out) reread = Image.open(out)
self.assertEqual('temp.tif', reread.tag_v2[269]) self.assertEqual("temp.tif", reread.tag_v2[269])
self.assertEqual('temp.tif', reread.tag[269][0]) self.assertEqual("temp.tif", reread.tag[269][0])
def test_12bit_rawmode(self): def test_12bit_rawmode(self):
""" Are we generating the same interpretation """ Are we generating the same interpretation
of the image as Imagemagick is? """ of the image as Imagemagick is? """
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
im = Image.open('Tests/images/12bit.cropped.tif') im = Image.open("Tests/images/12bit.cropped.tif")
im.load() im.load()
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False
# to make the target -- # to make the target --
@ -372,18 +375,19 @@ class TestFileLibTiff(LibTiffTestCase):
# imagemagick will auto scale so that a 12bit FFF is 16bit FFF0, # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,
# so we need to unshift so that the integer values are the same. # so we need to unshift so that the integer values are the same.
self.assert_image_equal_tofile(im, 'Tests/images/12in16bit.tif') self.assert_image_equal_tofile(im, "Tests/images/12in16bit.tif")
def test_blur(self): def test_blur(self):
# test case from irc, how to do blur on b/w image # test case from irc, how to do blur on b/w image
# and save to compressed tif. # and save to compressed tif.
from PIL import ImageFilter from PIL import ImageFilter
out = self.tempfile('temp.tif')
im = Image.open('Tests/images/pport_g4.tif') out = self.tempfile("temp.tif")
im = im.convert('L') im = Image.open("Tests/images/pport_g4.tif")
im = im.convert("L")
im = im.filter(ImageFilter.GaussianBlur(4)) im = im.filter(ImageFilter.GaussianBlur(4))
im.save(out, compression='tiff_adobe_deflate') im.save(out, compression="tiff_adobe_deflate")
im2 = Image.open(out) im2 = Image.open(out)
im2.load() im2.load()
@ -391,23 +395,23 @@ class TestFileLibTiff(LibTiffTestCase):
self.assert_image_equal(im, im2) self.assert_image_equal(im, im2)
def test_compressions(self): def test_compressions(self):
im = hopper('RGB') im = hopper("RGB")
out = self.tempfile('temp.tif') out = self.tempfile("temp.tif")
for compression in ('packbits', 'tiff_lzw'): for compression in ("packbits", "tiff_lzw"):
im.save(out, compression=compression) im.save(out, compression=compression)
im2 = Image.open(out) im2 = Image.open(out)
self.assert_image_equal(im, im2) self.assert_image_equal(im, im2)
im.save(out, compression='jpeg') im.save(out, compression="jpeg")
im2 = Image.open(out) im2 = Image.open(out)
self.assert_image_similar(im, im2, 30) self.assert_image_similar(im, im2, 30)
def test_cmyk_save(self): def test_cmyk_save(self):
im = hopper('CMYK') im = hopper("CMYK")
out = self.tempfile('temp.tif') out = self.tempfile("temp.tif")
im.save(out, compression='tiff_adobe_deflate') im.save(out, compression="tiff_adobe_deflate")
im2 = Image.open(out) im2 = Image.open(out)
self.assert_image_equal(im, im2) self.assert_image_equal(im, im2)
@ -416,12 +420,12 @@ class TestFileLibTiff(LibTiffTestCase):
to output on stderr from the error thrown by libtiff. We need to to output on stderr from the error thrown by libtiff. We need to
capture that but not now""" capture that but not now"""
im = hopper('RGB') im = hopper("RGB")
out = self.tempfile('temp.tif') out = self.tempfile("temp.tif")
self.assertRaises(IOError, im.save, out, compression='tiff_ccitt') self.assertRaises(IOError, im.save, out, compression="tiff_ccitt")
self.assertRaises(IOError, im.save, out, compression='group3') self.assertRaises(IOError, im.save, out, compression="group3")
self.assertRaises(IOError, im.save, out, compression='group4') self.assertRaises(IOError, im.save, out, compression="group4")
def test_fp_leak(self): def test_fp_leak(self):
im = Image.open("Tests/images/hopper_g4_500.tif") im = Image.open("Tests/images/hopper_g4_500.tif")
@ -437,30 +441,30 @@ class TestFileLibTiff(LibTiffTestCase):
def test_multipage(self): def test_multipage(self):
# issue #862 # issue #862
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
im = Image.open('Tests/images/multipage.tiff') im = Image.open("Tests/images/multipage.tiff")
# file is a multipage tiff, 10x10 green, 10x10 red, 20x20 blue # file is a multipage tiff, 10x10 green, 10x10 red, 20x20 blue
im.seek(0) im.seek(0)
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 128, 0))
self.assertTrue(im.tag.next) self.assertTrue(im.tag.next)
im.seek(1) im.seek(1)
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (255, 0, 0))
self.assertTrue(im.tag.next) self.assertTrue(im.tag.next)
im.seek(2) im.seek(2)
self.assertFalse(im.tag.next) self.assertFalse(im.tag.next)
self.assertEqual(im.size, (20, 20)) self.assertEqual(im.size, (20, 20))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 0, 255))
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False
def test_multipage_nframes(self): def test_multipage_nframes(self):
# issue #862 # issue #862
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
im = Image.open('Tests/images/multipage.tiff') im = Image.open("Tests/images/multipage.tiff")
frames = im.n_frames frames = im.n_frames
self.assertEqual(frames, 3) self.assertEqual(frames, 3)
for _ in range(frames): for _ in range(frames):
@ -472,7 +476,7 @@ class TestFileLibTiff(LibTiffTestCase):
def test__next(self): def test__next(self):
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
im = Image.open('Tests/images/hopper.tif') im = Image.open("Tests/images/hopper.tif")
self.assertFalse(im.tag.next) self.assertFalse(im.tag.next)
im.load() im.load()
self.assertFalse(im.tag.next) self.assertFalse(im.tag.next)
@ -501,7 +505,7 @@ class TestFileLibTiff(LibTiffTestCase):
"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2I.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2R.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif",
) ),
), ),
( (
7.3, # epsilon 7.3, # epsilon
@ -510,7 +514,7 @@ class TestFileLibTiff(LibTiffTestCase):
"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4I.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4R.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif",
) ),
), ),
) )
original = hopper("L") original = hopper("L")
@ -545,7 +549,7 @@ class TestFileLibTiff(LibTiffTestCase):
self.assert_image_similar(pilim, pilim_load, 0) self.assert_image_similar(pilim, pilim_load, 0)
save_bytesio() save_bytesio()
save_bytesio('raw') save_bytesio("raw")
save_bytesio("packbits") save_bytesio("packbits")
save_bytesio("tiff_lzw") save_bytesio("tiff_lzw")
@ -554,12 +558,12 @@ class TestFileLibTiff(LibTiffTestCase):
def test_crashing_metadata(self): def test_crashing_metadata(self):
# issue 1597 # issue 1597
im = Image.open('Tests/images/rdf.tif') im = Image.open("Tests/images/rdf.tif")
out = self.tempfile('temp.tif') out = self.tempfile("temp.tif")
TiffImagePlugin.WRITE_LIBTIFF = True TiffImagePlugin.WRITE_LIBTIFF = True
# this shouldn't crash # this shouldn't crash
im.save(out, format='TIFF') im.save(out, format="TIFF")
TiffImagePlugin.WRITE_LIBTIFF = False TiffImagePlugin.WRITE_LIBTIFF = False
def test_page_number_x_0(self): def test_page_number_x_0(self):
@ -580,8 +584,8 @@ class TestFileLibTiff(LibTiffTestCase):
# https://github.com/python-pillow/Pillow/issues/1651 # https://github.com/python-pillow/Pillow/issues/1651
tmpfile = self.tempfile("temp.tif") tmpfile = self.tempfile("temp.tif")
with open(tmpfile, 'wb') as f: with open(tmpfile, "wb") as f:
with open("Tests/images/g4-multi.tiff", 'rb') as src: with open("Tests/images/g4-multi.tiff", "rb") as src:
f.write(src.read()) f.write(src.read())
im = Image.open(tmpfile) im = Image.open(tmpfile)
@ -592,29 +596,29 @@ class TestFileLibTiff(LibTiffTestCase):
def test_read_icc(self): def test_read_icc(self):
with Image.open("Tests/images/hopper.iccprofile.tif") as img: with Image.open("Tests/images/hopper.iccprofile.tif") as img:
icc = img.info.get('icc_profile') icc = img.info.get("icc_profile")
self.assertIsNotNone(icc) self.assertIsNotNone(icc)
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/hopper.iccprofile.tif") as img: with Image.open("Tests/images/hopper.iccprofile.tif") as img:
icc_libtiff = img.info.get('icc_profile') icc_libtiff = img.info.get("icc_profile")
self.assertIsNotNone(icc_libtiff) self.assertIsNotNone(icc_libtiff)
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False
self.assertEqual(icc, icc_libtiff) self.assertEqual(icc, icc_libtiff)
def test_multipage_compression(self): def test_multipage_compression(self):
im = Image.open('Tests/images/compression.tif') im = Image.open("Tests/images/compression.tif")
im.seek(0) im.seek(0)
self.assertEqual(im._compression, 'tiff_ccitt') self.assertEqual(im._compression, "tiff_ccitt")
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
im.seek(1) im.seek(1)
self.assertEqual(im._compression, 'packbits') self.assertEqual(im._compression, "packbits")
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
im.load() im.load()
im.seek(0) im.seek(0)
self.assertEqual(im._compression, 'tiff_ccitt') self.assertEqual(im._compression, "tiff_ccitt")
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
im.load() im.load()
@ -638,13 +642,18 @@ class TestFileLibTiff(LibTiffTestCase):
self.assertEqual(im.size, (100, 40)) self.assertEqual(im.size, (100, 40))
self.assertEqual( self.assertEqual(
im.tile, im.tile,
[('tiff_adobe_deflate', (0, 0, 100, 40), 0, [
('RGB;16N', 'tiff_adobe_deflate', False))] (
"tiff_adobe_deflate",
(0, 0, 100, 40),
0,
("RGB;16N", "tiff_adobe_deflate", False),
)
],
) )
im.load() im.load()
self.assert_image_equal_tofile( self.assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGB_target.png")
im, "Tests/images/tiff_16bit_RGB_target.png")
def test_16bit_RGBa_tiff(self): def test_16bit_RGBa_tiff(self):
im = Image.open("Tests/images/tiff_16bit_RGBa.tiff") im = Image.open("Tests/images/tiff_16bit_RGBa.tiff")
@ -652,13 +661,11 @@ class TestFileLibTiff(LibTiffTestCase):
self.assertEqual(im.mode, "RGBA") self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (100, 40)) self.assertEqual(im.size, (100, 40))
self.assertEqual( self.assertEqual(
im.tile, im.tile, [("tiff_lzw", (0, 0, 100, 40), 0, ("RGBa;16N", "tiff_lzw", False))]
[('tiff_lzw', (0, 0, 100, 40), 0, ('RGBa;16N', 'tiff_lzw', False))]
) )
im.load() im.load()
self.assert_image_equal_tofile( self.assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png")
im, "Tests/images/tiff_16bit_RGBa_target.png")
def test_gimp_tiff(self): def test_gimp_tiff(self):
# Read TIFF JPEG images from GIMP [@PIL168] # Read TIFF JPEG images from GIMP [@PIL168]
@ -673,7 +680,7 @@ class TestFileLibTiff(LibTiffTestCase):
self.assertEqual(im.mode, "RGB") self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (256, 256)) self.assertEqual(im.size, (256, 256))
self.assertEqual( self.assertEqual(
im.tile, [('jpeg', (0, 0, 256, 256), 0, ('RGB', 'jpeg', False))] im.tile, [("jpeg", (0, 0, 256, 256), 0, ("RGB", "jpeg", False))]
) )
im.load() im.load()
@ -682,15 +689,14 @@ class TestFileLibTiff(LibTiffTestCase):
def test_sampleformat(self): def test_sampleformat(self):
# https://github.com/python-pillow/Pillow/issues/1466 # https://github.com/python-pillow/Pillow/issues/1466
im = Image.open("Tests/images/copyleft.tiff") im = Image.open("Tests/images/copyleft.tiff")
self.assertEqual(im.mode, 'RGB') self.assertEqual(im.mode, "RGB")
self.assert_image_equal_tofile(im, "Tests/images/copyleft.png", self.assert_image_equal_tofile(im, "Tests/images/copyleft.png", mode="RGB")
mode='RGB')
def test_lzw(self): def test_lzw(self):
im = Image.open("Tests/images/hopper_lzw.tif") im = Image.open("Tests/images/hopper_lzw.tif")
self.assertEqual(im.mode, 'RGB') self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128)) self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "TIFF") self.assertEqual(im.format, "TIFF")
im2 = hopper() im2 = hopper()
@ -742,5 +748,6 @@ class TestFileLibTiff(LibTiffTestCase):
infile = "Tests/images/old-style-jpeg-compression.tif" infile = "Tests/images/old-style-jpeg-compression.tif"
im = Image.open(infile) im = Image.open(infile)
self.assert_image_equal_tofile(im, self.assert_image_equal_tofile(
"Tests/images/old-style-jpeg-compression.png") im, "Tests/images/old-style-jpeg-compression.png"
)

View File

@ -17,7 +17,7 @@ class TestFileLibTiffSmall(LibTiffTestCase):
"""Testing the open file load path""" """Testing the open file load path"""
test_file = "Tests/images/hopper_g4.tif" test_file = "Tests/images/hopper_g4.tif"
with open(test_file, 'rb') as f: with open(test_file, "rb") as f:
im = Image.open(f) im = Image.open(f)
self.assertEqual(im.size, (128, 128)) self.assertEqual(im.size, (128, 128))
@ -26,9 +26,10 @@ class TestFileLibTiffSmall(LibTiffTestCase):
def test_g4_hopper_bytesio(self): def test_g4_hopper_bytesio(self):
"""Testing the bytesio loading code path""" """Testing the bytesio loading code path"""
from io import BytesIO from io import BytesIO
test_file = "Tests/images/hopper_g4.tif" test_file = "Tests/images/hopper_g4.tif"
s = BytesIO() s = BytesIO()
with open(test_file, 'rb') as f: with open(test_file, "rb") as f:
s.write(f.read()) s.write(f.read())
s.seek(0) s.seek(0)
im = Image.open(s) im = Image.open(s)

View File

@ -4,12 +4,10 @@ from PIL import Image, McIdasImagePlugin
class TestFileMcIdas(PillowTestCase): 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(SyntaxError, McIdasImagePlugin.McIdasImageFile, invalid_file)
McIdasImagePlugin.McIdasImageFile, invalid_file)
def test_valid_file(self): def test_valid_file(self):
# Arrange # Arrange

View File

@ -13,9 +13,8 @@ TEST_FILE = "Tests/images/hopper.mic"
@unittest.skipUnless(olefile_installed, "olefile package not installed") @unittest.skipUnless(olefile_installed, "olefile package not installed")
@unittest.skipUnless(features.check('libtiff'), "libtiff not installed") @unittest.skipUnless(features.check("libtiff"), "libtiff not installed")
class TestFileMic(PillowTestCase): class TestFileMic(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
im.load() im.load()
@ -24,8 +23,8 @@ class TestFileMic(PillowTestCase):
self.assertEqual(im.format, "MIC") self.assertEqual(im.format, "MIC")
# Adjust for the gamma of 2.2 encoded into the file # Adjust for the gamma of 2.2 encoded into the file
lut = ImagePalette.make_gamma_lut(1/2.2) lut = ImagePalette.make_gamma_lut(1 / 2.2)
im = Image.merge('RGBA', [chan.point(lut) for chan in im.split()]) im = Image.merge("RGBA", [chan.point(lut) for chan in im.split()])
im2 = hopper("RGBA") im2 = hopper("RGBA")
self.assert_image_similar(im, im2, 10) self.assert_image_similar(im, im2, 10)
@ -57,10 +56,8 @@ 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(SyntaxError, MicImagePlugin.MicImageFile, invalid_file)
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(SyntaxError, MicImagePlugin.MicImageFile, ole_file)
MicImagePlugin.MicImageFile, ole_file)

View File

@ -7,7 +7,6 @@ test_files = ["Tests/images/sugarshack.mpo", "Tests/images/frozenpond.mpo"]
class TestFileMpo(PillowTestCase): class TestFileMpo(PillowTestCase):
def setUp(self): def setUp(self):
codecs = dir(Image.core) codecs = dir(Image.core)
if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs: if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:
@ -35,23 +34,25 @@ class TestFileMpo(PillowTestCase):
def open(): def open():
im = Image.open(test_files[0]) im = Image.open(test_files[0])
im.load() im.load()
self.assert_warning(None, open) self.assert_warning(None, open)
def test_app(self): def test_app(self):
for test_file in test_files: for test_file in test_files:
# Test APP/COM reader (@PIL135) # Test APP/COM reader (@PIL135)
im = Image.open(test_file) im = Image.open(test_file)
self.assertEqual(im.applist[0][0], 'APP1') self.assertEqual(im.applist[0][0], "APP1")
self.assertEqual(im.applist[1][0], 'APP2') self.assertEqual(im.applist[1][0], "APP2")
self.assertEqual(im.applist[1][1][:16], self.assertEqual(
b'MPF\x00MM\x00*\x00\x00\x00\x08\x00\x03\xb0\x00') im.applist[1][1][:16], b"MPF\x00MM\x00*\x00\x00\x00\x08\x00\x03\xb0\x00"
)
self.assertEqual(len(im.applist), 2) self.assertEqual(len(im.applist), 2)
def test_exif(self): def test_exif(self):
for test_file in test_files: for test_file in test_files:
im = Image.open(test_file) im = Image.open(test_file)
info = im._getexif() info = im._getexif()
self.assertEqual(info[272], 'Nintendo 3DS') self.assertEqual(info[272], "Nintendo 3DS")
self.assertEqual(info[296], 2) self.assertEqual(info[296], 2)
self.assertEqual(info[34665], 188) self.assertEqual(info[34665], 188)
@ -68,19 +69,19 @@ class TestFileMpo(PillowTestCase):
# Nintendo # Nintendo
im = Image.open("Tests/images/sugarshack.mpo") im = Image.open("Tests/images/sugarshack.mpo")
exif = im.getexif() exif = im.getexif()
self.assertEqual(exif.get_ifd(0x927c)[0x1101]["Parallax"], -44.798187255859375) self.assertEqual(exif.get_ifd(0x927C)[0x1101]["Parallax"], -44.798187255859375)
# Fujifilm # Fujifilm
im = Image.open("Tests/images/fujifilm.mpo") im = Image.open("Tests/images/fujifilm.mpo")
im.seek(1) im.seek(1)
exif = im.getexif() exif = im.getexif()
self.assertEqual(exif.get_ifd(0x927c)[0xb211], -3.125) self.assertEqual(exif.get_ifd(0x927C)[0xB211], -3.125)
def test_mp(self): def test_mp(self):
for test_file in test_files: for test_file in test_files:
im = Image.open(test_file) im = Image.open(test_file)
mpinfo = im._getmp() mpinfo = im._getmp()
self.assertEqual(mpinfo[45056], b'0100') self.assertEqual(mpinfo[45056], b"0100")
self.assertEqual(mpinfo[45057], 2) self.assertEqual(mpinfo[45057], 2)
def test_mp_offset(self): def test_mp_offset(self):
@ -88,7 +89,7 @@ class TestFileMpo(PillowTestCase):
# in APP2 data, in contrast to normal 8 # in APP2 data, in contrast to normal 8
im = Image.open("Tests/images/sugarshack_ifd_offset.mpo") im = Image.open("Tests/images/sugarshack_ifd_offset.mpo")
mpinfo = im._getmp() mpinfo = im._getmp()
self.assertEqual(mpinfo[45056], b'0100') self.assertEqual(mpinfo[45056], b"0100")
self.assertEqual(mpinfo[45057], 2) self.assertEqual(mpinfo[45057], 2)
def test_mp_attribute(self): def test_mp_attribute(self):
@ -97,17 +98,16 @@ class TestFileMpo(PillowTestCase):
mpinfo = im._getmp() mpinfo = im._getmp()
frameNumber = 0 frameNumber = 0
for mpentry in mpinfo[45058]: for mpentry in mpinfo[45058]:
mpattr = mpentry['Attribute'] mpattr = mpentry["Attribute"]
if frameNumber: if frameNumber:
self.assertFalse(mpattr['RepresentativeImageFlag']) self.assertFalse(mpattr["RepresentativeImageFlag"])
else: else:
self.assertTrue(mpattr['RepresentativeImageFlag']) self.assertTrue(mpattr["RepresentativeImageFlag"])
self.assertFalse(mpattr['DependentParentImageFlag']) self.assertFalse(mpattr["DependentParentImageFlag"])
self.assertFalse(mpattr['DependentChildImageFlag']) self.assertFalse(mpattr["DependentChildImageFlag"])
self.assertEqual(mpattr['ImageDataFormat'], 'JPEG') self.assertEqual(mpattr["ImageDataFormat"], "JPEG")
self.assertEqual(mpattr['MPType'], self.assertEqual(mpattr["MPType"], "Multi-Frame Image: (Disparity)")
'Multi-Frame Image: (Disparity)') self.assertEqual(mpattr["Reserved"], 0)
self.assertEqual(mpattr['Reserved'], 0)
frameNumber += 1 frameNumber += 1
def test_seek(self): def test_seek(self):
@ -144,7 +144,7 @@ class TestFileMpo(PillowTestCase):
self.assertLess(im.tell(), n_frames) self.assertLess(im.tell(), n_frames)
# Test that seeking to the last frame does not raise an error # Test that seeking to the last frame does not raise an error
im.seek(n_frames-1) im.seek(n_frames - 1)
def test_image_grab(self): def test_image_grab(self):
for test_file in test_files: for test_file in test_files:

View File

@ -10,7 +10,6 @@ YA_EXTRA_DIR = "Tests/images/msp"
class TestFileMsp(PillowTestCase): class TestFileMsp(PillowTestCase):
def test_sanity(self): def test_sanity(self):
test_file = self.tempfile("temp.msp") test_file = self.tempfile("temp.msp")
@ -25,8 +24,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(SyntaxError, MspImagePlugin.MspImageFile, invalid_file)
MspImagePlugin.MspImageFile, invalid_file)
def test_bad_checksum(self): def test_bad_checksum(self):
# Arrange # Arrange
@ -34,8 +32,7 @@ class TestFileMsp(PillowTestCase):
bad_checksum = "Tests/images/hopper_bad_checksum.msp" bad_checksum = "Tests/images/hopper_bad_checksum.msp"
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError, MspImagePlugin.MspImageFile, bad_checksum)
MspImagePlugin.MspImageFile, bad_checksum)
def test_open_windows_v1(self): def test_open_windows_v1(self):
# Arrange # Arrange
@ -51,25 +48,26 @@ class TestFileMsp(PillowTestCase):
target = Image.open(target_path) target = Image.open(target_path)
self.assert_image_equal(im, target) self.assert_image_equal(im, target)
@unittest.skipIf(not os.path.exists(EXTRA_DIR), @unittest.skipIf(not os.path.exists(EXTRA_DIR), "Extra image files not installed")
"Extra image files not installed")
def test_open_windows_v2(self): def test_open_windows_v2(self):
files = (os.path.join(EXTRA_DIR, f) for f in os.listdir(EXTRA_DIR) files = (
if os.path.splitext(f)[1] == '.msp') os.path.join(EXTRA_DIR, f)
for f in os.listdir(EXTRA_DIR)
if os.path.splitext(f)[1] == ".msp"
)
for path in files: for path in files:
self._assert_file_image_equal(path, self._assert_file_image_equal(path, path.replace(".msp", ".png"))
path.replace('.msp', '.png'))
@unittest.skipIf(not os.path.exists(YA_EXTRA_DIR), @unittest.skipIf(
"Even More Extra image files not installed") not os.path.exists(YA_EXTRA_DIR), "Even More Extra image files not installed"
)
def test_msp_v2(self): def test_msp_v2(self):
for f in os.listdir(YA_EXTRA_DIR): for f in os.listdir(YA_EXTRA_DIR):
if '.MSP' not in f: if ".MSP" not in f:
continue continue
path = os.path.join(YA_EXTRA_DIR, f) path = os.path.join(YA_EXTRA_DIR, f)
self._assert_file_image_equal(path, self._assert_file_image_equal(path, path.replace(".MSP", ".png"))
path.replace('.MSP', '.png'))
def test_cannot_save_wrong_mode(self): def test_cannot_save_wrong_mode(self):
# Arrange # Arrange

View File

@ -3,9 +3,8 @@ from PIL import Image
class TestFilePcd(PillowTestCase): class TestFilePcd(PillowTestCase):
def test_load_raw(self): def test_load_raw(self):
im = Image.open('Tests/images/hopper.pcd') im = Image.open("Tests/images/hopper.pcd")
im.load() # should not segfault. im.load() # should not segfault.
# Note that this image was created with a resized hopper # Note that this image was created with a resized hopper

View File

@ -4,7 +4,6 @@ from PIL import Image, ImageFile, PcxImagePlugin
class TestFilePcx(PillowTestCase): class TestFilePcx(PillowTestCase):
def _roundtrip(self, im): def _roundtrip(self, im):
f = self.tempfile("temp.pcx") f = self.tempfile("temp.pcx")
im.save(f) im.save(f)
@ -17,7 +16,7 @@ class TestFilePcx(PillowTestCase):
self.assert_image_equal(im2, im) self.assert_image_equal(im2, im)
def test_sanity(self): def test_sanity(self):
for mode in ('1', 'L', 'P', 'RGB'): for mode in ("1", "L", "P", "RGB"):
self._roundtrip(hopper(mode)) self._roundtrip(hopper(mode))
# Test an unsupported mode # Test an unsupported mode
@ -28,14 +27,13 @@ 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(SyntaxError, PcxImagePlugin.PcxImageFile, invalid_file)
PcxImagePlugin.PcxImageFile, invalid_file)
def test_odd(self): def test_odd(self):
# see issue #523, odd sized images should have a stride that's even. # see issue #523, odd sized images should have a stride that's even.
# not that imagemagick or gimp write pcx that way. # not that imagemagick or gimp write pcx that way.
# we were not handling properly. # we were not handling properly.
for mode in ('1', 'L', 'P', 'RGB'): for mode in ("1", "L", "P", "RGB"):
# larger, odd sized images are better here to ensure that # larger, odd sized images are better here to ensure that
# we handle interrupted scan lines properly. # we handle interrupted scan lines properly.
self._roundtrip(hopper(mode).resize((511, 511))) self._roundtrip(hopper(mode).resize((511, 511)))
@ -50,17 +48,17 @@ class TestFilePcx(PillowTestCase):
self.assertEqual(im.tile[0][1], (0, 0, 447, 144)) self.assertEqual(im.tile[0][1], (0, 0, 447, 144))
# Make sure all pixels are either 0 or 255. # Make sure all pixels are either 0 or 255.
self.assertEqual(im.histogram()[0] + im.histogram()[255], 447*144) self.assertEqual(im.histogram()[0] + im.histogram()[255], 447 * 144)
def test_1px_width(self): def test_1px_width(self):
im = Image.new('L', (1, 256)) im = Image.new("L", (1, 256))
px = im.load() px = im.load()
for y in range(256): for y in range(256):
px[0, y] = y px[0, y] = y
self._roundtrip(im) self._roundtrip(im)
def test_large_count(self): def test_large_count(self):
im = Image.new('L', (256, 1)) im = Image.new("L", (256, 1))
px = im.load() px = im.load()
for x in range(256): for x in range(256):
px[x, 0] = x // 67 * 67 px[x, 0] = x // 67 * 67
@ -75,7 +73,7 @@ class TestFilePcx(PillowTestCase):
ImageFile.MAXBLOCK = _last ImageFile.MAXBLOCK = _last
def test_break_in_count_overflow(self): def test_break_in_count_overflow(self):
im = Image.new('L', (256, 5)) im = Image.new("L", (256, 5))
px = im.load() px = im.load()
for y in range(4): for y in range(4):
for x in range(256): for x in range(256):
@ -83,7 +81,7 @@ class TestFilePcx(PillowTestCase):
self._test_buffer_overflow(im) self._test_buffer_overflow(im)
def test_break_one_in_loop(self): def test_break_one_in_loop(self):
im = Image.new('L', (256, 5)) im = Image.new("L", (256, 5))
px = im.load() px = im.load()
for y in range(5): for y in range(5):
for x in range(256): for x in range(256):
@ -91,7 +89,7 @@ class TestFilePcx(PillowTestCase):
self._test_buffer_overflow(im) self._test_buffer_overflow(im)
def test_break_many_in_loop(self): def test_break_many_in_loop(self):
im = Image.new('L', (256, 5)) im = Image.new("L", (256, 5))
px = im.load() px = im.load()
for y in range(4): for y in range(4):
for x in range(256): for x in range(256):
@ -101,7 +99,7 @@ class TestFilePcx(PillowTestCase):
self._test_buffer_overflow(im) self._test_buffer_overflow(im)
def test_break_one_at_end(self): def test_break_one_at_end(self):
im = Image.new('L', (256, 5)) im = Image.new("L", (256, 5))
px = im.load() px = im.load()
for y in range(5): for y in range(5):
for x in range(256): for x in range(256):
@ -110,7 +108,7 @@ class TestFilePcx(PillowTestCase):
self._test_buffer_overflow(im) self._test_buffer_overflow(im)
def test_break_many_at_end(self): def test_break_many_at_end(self):
im = Image.new('L', (256, 5)) im = Image.new("L", (256, 5))
px = im.load() px = im.load()
for y in range(5): for y in range(5):
for x in range(256): for x in range(256):
@ -121,7 +119,7 @@ class TestFilePcx(PillowTestCase):
self._test_buffer_overflow(im) self._test_buffer_overflow(im)
def test_break_padding(self): def test_break_padding(self):
im = Image.new('L', (257, 5)) im = Image.new("L", (257, 5))
px = im.load() px = im.load()
for y in range(5): for y in range(5):
for x in range(257): for x in range(257):

View File

@ -8,7 +8,6 @@ import time
class TestFilePdf(PillowTestCase): class TestFilePdf(PillowTestCase):
def helper_save_as_pdf(self, mode, **kwargs): def helper_save_as_pdf(self, mode, **kwargs):
# Arrange # Arrange
im = hopper(mode) im = hopper(mode)
@ -21,15 +20,16 @@ class TestFilePdf(PillowTestCase):
self.assertTrue(os.path.isfile(outfile)) self.assertTrue(os.path.isfile(outfile))
self.assertGreater(os.path.getsize(outfile), 0) self.assertGreater(os.path.getsize(outfile), 0)
with PdfParser.PdfParser(outfile) as pdf: with PdfParser.PdfParser(outfile) as pdf:
if kwargs.get("append_images", False) or \ if kwargs.get("append_images", False) or kwargs.get("append", False):
kwargs.get("append", False):
self.assertGreater(len(pdf.pages), 1) self.assertGreater(len(pdf.pages), 1)
else: else:
self.assertGreater(len(pdf.pages), 0) self.assertGreater(len(pdf.pages), 0)
with open(outfile, 'rb') as fp: with open(outfile, "rb") as fp:
contents = fp.read() contents = fp.read()
size = tuple(int(d) for d in size = tuple(
contents.split(b'/MediaBox [ 0 0 ')[1].split(b']')[0].split()) int(d)
for d in contents.split(b"/MediaBox [ 0 0 ")[1].split(b"]")[0].split()
)
self.assertEqual(im.size, size) self.assertEqual(im.size, size)
return outfile return outfile
@ -82,7 +82,7 @@ class TestFilePdf(PillowTestCase):
# Multiframe image # Multiframe image
im = Image.open("Tests/images/dispose_bgnd.gif") im = Image.open("Tests/images/dispose_bgnd.gif")
outfile = self.tempfile('temp.pdf') outfile = self.tempfile("temp.pdf")
im.save(outfile, save_all=True) im.save(outfile, save_all=True)
self.assertTrue(os.path.isfile(outfile)) self.assertTrue(os.path.isfile(outfile))
@ -99,6 +99,7 @@ class TestFilePdf(PillowTestCase):
def imGenerator(ims): def imGenerator(ims):
for im in ims: for im in ims:
yield im yield im
im.save(outfile, save_all=True, append_images=imGenerator(ims)) im.save(outfile, save_all=True, append_images=imGenerator(ims))
self.assertTrue(os.path.isfile(outfile)) self.assertTrue(os.path.isfile(outfile))
@ -115,7 +116,7 @@ class TestFilePdf(PillowTestCase):
# Test saving a multiframe image without save_all # Test saving a multiframe image without save_all
im = Image.open("Tests/images/dispose_bgnd.gif") im = Image.open("Tests/images/dispose_bgnd.gif")
outfile = self.tempfile('temp.pdf') outfile = self.tempfile("temp.pdf")
im.save(outfile) im.save(outfile)
self.assertTrue(os.path.isfile(outfile)) self.assertTrue(os.path.isfile(outfile))
@ -124,8 +125,8 @@ class TestFilePdf(PillowTestCase):
def test_pdf_open(self): def test_pdf_open(self):
# fail on a buffer full of null bytes # fail on a buffer full of null bytes
self.assertRaises( self.assertRaises(
PdfParser.PdfFormatError, PdfParser.PdfFormatError, PdfParser.PdfParser, buf=bytearray(65536)
PdfParser.PdfParser, buf=bytearray(65536)) )
# make an empty PDF object # make an empty PDF object
with PdfParser.PdfParser() as empty_pdf: with PdfParser.PdfParser() as empty_pdf:
@ -162,10 +163,9 @@ class TestFilePdf(PillowTestCase):
im = hopper("RGB") im = hopper("RGB")
temp_dir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
try: try:
self.assertRaises(IOError, self.assertRaises(
im.save, IOError, im.save, os.path.join(temp_dir, "nonexistent.pdf"), append=True
os.path.join(temp_dir, "nonexistent.pdf"), )
append=True)
finally: finally:
os.rmdir(temp_dir) os.rmdir(temp_dir)
@ -194,9 +194,9 @@ class TestFilePdf(PillowTestCase):
with PdfParser.PdfParser(pdf_filename, mode="r+b") as pdf: with PdfParser.PdfParser(pdf_filename, mode="r+b") as pdf:
self.assertEqual(len(pdf.pages), 1) self.assertEqual(len(pdf.pages), 1)
self.assertEqual(len(pdf.info), 4) self.assertEqual(len(pdf.info), 4)
self.assertEqual(pdf.info.Title, os.path.splitext( self.assertEqual(
os.path.basename(pdf_filename) pdf.info.Title, os.path.splitext(os.path.basename(pdf_filename))[0]
)[0]) )
self.assertEqual(pdf.info.Producer, "PdfParser") self.assertEqual(pdf.info.Producer, "PdfParser")
self.assertIn(b"CreationDate", pdf.info) self.assertIn(b"CreationDate", pdf.info)
self.assertIn(b"ModDate", pdf.info) self.assertIn(b"ModDate", pdf.info)
@ -223,8 +223,7 @@ class TestFilePdf(PillowTestCase):
# append two images # append two images
mode_CMYK = hopper("CMYK") mode_CMYK = hopper("CMYK")
mode_P = hopper("P") mode_P = hopper("P")
mode_CMYK.save(pdf_filename, mode_CMYK.save(pdf_filename, append=True, save_all=True, append_images=[mode_P])
append=True, save_all=True, append_images=[mode_P])
# open the PDF again, check pages and info again # open the PDF again, check pages and info again
with PdfParser.PdfParser(pdf_filename) as pdf: with PdfParser.PdfParser(pdf_filename) as pdf:
@ -242,10 +241,16 @@ class TestFilePdf(PillowTestCase):
def test_pdf_info(self): def test_pdf_info(self):
# make a PDF file # make a PDF file
pdf_filename = self.helper_save_as_pdf( pdf_filename = self.helper_save_as_pdf(
"RGB", title="title", author="author", subject="subject", "RGB",
keywords="keywords", creator="creator", producer="producer", title="title",
author="author",
subject="subject",
keywords="keywords",
creator="creator",
producer="producer",
creationDate=time.strptime("2000", "%Y"), creationDate=time.strptime("2000", "%Y"),
modDate=time.strptime("2001", "%Y")) modDate=time.strptime("2001", "%Y"),
)
# open it, check pages and info # open it, check pages and info
with PdfParser.PdfParser(pdf_filename) as pdf: with PdfParser.PdfParser(pdf_filename) as pdf:
@ -256,8 +261,7 @@ class TestFilePdf(PillowTestCase):
self.assertEqual(pdf.info.Keywords, "keywords") self.assertEqual(pdf.info.Keywords, "keywords")
self.assertEqual(pdf.info.Creator, "creator") self.assertEqual(pdf.info.Creator, "creator")
self.assertEqual(pdf.info.Producer, "producer") self.assertEqual(pdf.info.Producer, "producer")
self.assertEqual(pdf.info.CreationDate, self.assertEqual(pdf.info.CreationDate, time.strptime("2000", "%Y"))
time.strptime("2000", "%Y"))
self.assertEqual(pdf.info.ModDate, time.strptime("2001", "%Y")) self.assertEqual(pdf.info.ModDate, time.strptime("2001", "%Y"))
self.check_pdf_pages_consistency(pdf) self.check_pdf_pages_consistency(pdf)

View File

@ -6,7 +6,6 @@ TEST_FILE = "Tests/images/hopper.pxr"
class TestFilePixar(PillowTestCase): class TestFilePixar(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
im.load() im.load()
@ -21,6 +20,4 @@ class TestFilePixar(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( self.assertRaises(SyntaxError, PixarImagePlugin.PixarImageFile, invalid_file)
SyntaxError,
PixarImagePlugin.PixarImageFile, invalid_file)

View File

@ -8,6 +8,7 @@ import sys
try: try:
from PIL import _webp from PIL import _webp
HAVE_WEBP = True HAVE_WEBP = True
except ImportError: except ImportError:
HAVE_WEBP = False HAVE_WEBP = False
@ -32,7 +33,7 @@ def chunk(cid, *data):
o32 = PngImagePlugin.o32 o32 = PngImagePlugin.o32
IHDR = chunk(b"IHDR", o32(1), o32(1), b'\x08\x02', b'\0\0\0') IHDR = chunk(b"IHDR", o32(1), o32(1), b"\x08\x02", b"\0\0\0")
IDAT = chunk(b"IDAT") IDAT = chunk(b"IDAT")
IEND = chunk(b"IEND") IEND = chunk(b"IEND")
@ -52,7 +53,6 @@ def roundtrip(im, **options):
class TestFilePng(PillowTestCase): class TestFilePng(PillowTestCase):
def setUp(self): def setUp(self):
if "zip_encoder" not in codecs or "zip_decoder" not in codecs: if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
self.skipTest("zip/deflate support not available") self.skipTest("zip/deflate support not available")
@ -86,7 +86,7 @@ class TestFilePng(PillowTestCase):
self.assertEqual(im.mode, "RGB") self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128)) self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "PNG") self.assertEqual(im.format, "PNG")
self.assertEqual(im.get_format_mimetype(), 'image/png') self.assertEqual(im.get_format_mimetype(), "image/png")
for mode in ["1", "L", "P", "RGB", "I", "I;16"]: for mode in ["1", "L", "P", "RGB", "I", "I;16"]:
im = hopper(mode) im = hopper(mode)
@ -99,8 +99,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(SyntaxError, PngImagePlugin.PngImageFile, invalid_file)
PngImagePlugin.PngImageFile, invalid_file)
def test_broken(self): def test_broken(self):
# Check reading of totally broken files. In this case, the test # Check reading of totally broken files. In this case, the test
@ -112,76 +111,83 @@ class TestFilePng(PillowTestCase):
def test_bad_text(self): def test_bad_text(self):
# Make sure PIL can read malformed tEXt chunks (@PIL152) # Make sure PIL can read malformed tEXt chunks (@PIL152)
im = load(HEAD + chunk(b'tEXt') + TAIL) im = load(HEAD + chunk(b"tEXt") + TAIL)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'tEXt', b'spam') + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam") + TAIL)
self.assertEqual(im.info, {'spam': ''}) self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'tEXt', b'spam\0') + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {'spam': ''}) self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'tEXt', b'spam\0egg') + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam\0egg") + TAIL)
self.assertEqual(im.info, {'spam': 'egg'}) self.assertEqual(im.info, {"spam": "egg"})
im = load(HEAD + chunk(b'tEXt', b'spam\0egg\0') + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam\0egg\0") + TAIL)
self.assertEqual(im.info, {'spam': 'egg\x00'}) self.assertEqual(im.info, {"spam": "egg\x00"})
def test_bad_ztxt(self): def test_bad_ztxt(self):
# Test reading malformed zTXt chunks (python-pillow/Pillow#318) # Test reading malformed zTXt chunks (python-pillow/Pillow#318)
im = load(HEAD + chunk(b'zTXt') + TAIL) im = load(HEAD + chunk(b"zTXt") + TAIL)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'zTXt', b'spam') + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam") + TAIL)
self.assertEqual(im.info, {'spam': ''}) self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'zTXt', b'spam\0') + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {'spam': ''}) self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'zTXt', b'spam\0\0') + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam\0\0") + TAIL)
self.assertEqual(im.info, {'spam': ''}) self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk( im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")[:1]) + TAIL)
b'zTXt', b'spam\0\0' + zlib.compress(b'egg')[:1]) + TAIL) self.assertEqual(im.info, {"spam": ""})
self.assertEqual(im.info, {'spam': ''})
im = load( im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")) + TAIL)
HEAD + chunk(b'zTXt', b'spam\0\0' + zlib.compress(b'egg')) + TAIL) self.assertEqual(im.info, {"spam": "egg"})
self.assertEqual(im.info, {'spam': 'egg'})
def test_bad_itxt(self): def test_bad_itxt(self):
im = load(HEAD + chunk(b'iTXt') + TAIL) im = load(HEAD + chunk(b"iTXt") + TAIL)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam') + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam") + TAIL)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0') + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0\x02') + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0\x02") + TAIL)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0\0\0foo\0') + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0foo\0") + TAIL)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0\0\0en\0Spam\0egg') + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0en\0Spam\0egg") + TAIL)
self.assertEqual(im.info, {"spam": "egg"}) self.assertEqual(im.info, {"spam": "egg"})
self.assertEqual(im.info["spam"].lang, "en") self.assertEqual(im.info["spam"].lang, "en")
self.assertEqual(im.info["spam"].tkey, "Spam") self.assertEqual(im.info["spam"].tkey, "Spam")
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' + im = load(
zlib.compress(b"egg")[:1]) + TAIL) HEAD
self.assertEqual(im.info, {'spam': ''}) + chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg")[:1])
+ TAIL
)
self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' + im = load(
zlib.compress(b"egg")) + TAIL) HEAD
+ chunk(b"iTXt", b"spam\0\1\1en\0Spam\0" + zlib.compress(b"egg"))
+ TAIL
)
self.assertEqual(im.info, {}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' + im = load(
zlib.compress(b"egg")) + TAIL) HEAD
+ chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg"))
+ TAIL
)
self.assertEqual(im.info, {"spam": "egg"}) self.assertEqual(im.info, {"spam": "egg"})
self.assertEqual(im.info["spam"].lang, "en") self.assertEqual(im.info["spam"].lang, "en")
self.assertEqual(im.info["spam"].tkey, "Spam") self.assertEqual(im.info["spam"].tkey, "Spam")
@ -213,7 +219,7 @@ class TestFilePng(PillowTestCase):
self.assert_image(im, "RGBA", (162, 150)) self.assert_image(im, "RGBA", (162, 150))
# image has 124 unique alpha values # image has 124 unique alpha values
self.assertEqual(len(im.getchannel('A').getcolors()), 124) self.assertEqual(len(im.getchannel("A").getcolors()), 124)
def test_load_transparent_rgb(self): def test_load_transparent_rgb(self):
test_file = "Tests/images/rgb_trns.png" test_file = "Tests/images/rgb_trns.png"
@ -225,7 +231,7 @@ class TestFilePng(PillowTestCase):
self.assert_image(im, "RGBA", (64, 64)) self.assert_image(im, "RGBA", (64, 64))
# image has 876 transparent pixels # image has 876 transparent pixels
self.assertEqual(im.getchannel('A').getcolors()[0][0], 876) self.assertEqual(im.getchannel("A").getcolors()[0][0], 876)
def test_save_p_transparent_palette(self): def test_save_p_transparent_palette(self):
in_file = "Tests/images/pil123p.png" in_file = "Tests/images/pil123p.png"
@ -247,7 +253,7 @@ class TestFilePng(PillowTestCase):
self.assert_image(im, "RGBA", (162, 150)) self.assert_image(im, "RGBA", (162, 150))
# image has 124 unique alpha values # image has 124 unique alpha values
self.assertEqual(len(im.getchannel('A').getcolors()), 124) self.assertEqual(len(im.getchannel("A").getcolors()), 124)
def test_save_p_single_transparency(self): def test_save_p_single_transparency(self):
in_file = "Tests/images/p_trns_single.png" in_file = "Tests/images/p_trns_single.png"
@ -271,7 +277,7 @@ class TestFilePng(PillowTestCase):
self.assertEqual(im.getpixel((31, 31)), (0, 255, 52, 0)) self.assertEqual(im.getpixel((31, 31)), (0, 255, 52, 0))
# image has 876 transparent pixels # image has 876 transparent pixels
self.assertEqual(im.getchannel('A').getcolors()[0][0], 876) self.assertEqual(im.getchannel("A").getcolors()[0][0], 876)
def test_save_p_transparent_black(self): def test_save_p_transparent_black(self):
# check if solid black image with full transparency # check if solid black image with full transparency
@ -292,19 +298,14 @@ class TestFilePng(PillowTestCase):
self.assertEqual(im.getcolors(), [(100, (0, 0, 0, 0))]) self.assertEqual(im.getcolors(), [(100, (0, 0, 0, 0))])
def test_save_greyscale_transparency(self): def test_save_greyscale_transparency(self):
for mode, num_transparent in { for mode, num_transparent in {"1": 1994, "L": 559, "I": 559}.items():
"1": 1994, in_file = "Tests/images/" + mode.lower() + "_trns.png"
"L": 559,
"I": 559,
}.items():
in_file = "Tests/images/"+mode.lower()+"_trns.png"
im = Image.open(in_file) im = Image.open(in_file)
self.assertEqual(im.mode, mode) self.assertEqual(im.mode, mode)
self.assertEqual(im.info["transparency"], 255) self.assertEqual(im.info["transparency"], 255)
im_rgba = im.convert('RGBA') im_rgba = im.convert("RGBA")
self.assertEqual( self.assertEqual(im_rgba.getchannel("A").getcolors()[0][0], num_transparent)
im_rgba.getchannel("A").getcolors()[0][0], num_transparent)
test_file = self.tempfile("temp.png") test_file = self.tempfile("temp.png")
im.save(test_file) im.save(test_file)
@ -314,9 +315,10 @@ class TestFilePng(PillowTestCase):
self.assertEqual(test_im.info["transparency"], 255) self.assertEqual(test_im.info["transparency"], 255)
self.assert_image_equal(im, test_im) self.assert_image_equal(im, test_im)
test_im_rgba = test_im.convert('RGBA') test_im_rgba = test_im.convert("RGBA")
self.assertEqual( self.assertEqual(
test_im_rgba.getchannel('A').getcolors()[0][0], num_transparent) test_im_rgba.getchannel("A").getcolors()[0][0], num_transparent
)
def test_save_rgb_single_transparency(self): def test_save_rgb_single_transparency(self):
in_file = "Tests/images/caption_6_33_22.png" in_file = "Tests/images/caption_6_33_22.png"
@ -345,7 +347,7 @@ class TestFilePng(PillowTestCase):
# -14: malformed chunk # -14: malformed chunk
for offset in (-10, -13, -14): for offset in (-10, -13, -14):
with open(TEST_PNG_FILE, 'rb') as f: with open(TEST_PNG_FILE, "rb") as f:
test_file = f.read()[:offset] test_file = f.read()[:offset]
im = Image.open(BytesIO(test_file)) im = Image.open(BytesIO(test_file))
@ -355,12 +357,11 @@ class TestFilePng(PillowTestCase):
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
chunk_data = chunk(b'tEXt', b'spam') chunk_data = chunk(b"tEXt", b"spam")
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, self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data))
BytesIO(image_data))
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
try: try:
@ -372,12 +373,13 @@ class TestFilePng(PillowTestCase):
def test_verify_not_ignores_crc_error_in_required_chunk(self): def test_verify_not_ignores_crc_error_in_required_chunk(self):
# check does not ignore crc errors in required chunks # check does not ignore crc errors in required chunks
image_data = MAGIC + IHDR[:-1] + b'q' + TAIL image_data = MAGIC + IHDR[:-1] + b"q" + TAIL
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
try: try:
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, self.assertRaises(
BytesIO(image_data)) SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data)
)
finally: finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False
@ -417,8 +419,8 @@ class TestFilePng(PillowTestCase):
info.add_text("ZIP", "VALUE", zip=True) info.add_text("ZIP", "VALUE", zip=True)
im = roundtrip(im, pnginfo=info) im = roundtrip(im, pnginfo=info)
self.assertEqual(im.info, {'TXT': 'VALUE', 'ZIP': 'VALUE'}) self.assertEqual(im.info, {"TXT": "VALUE", "ZIP": "VALUE"})
self.assertEqual(im.text, {'TXT': 'VALUE', 'ZIP': 'VALUE'}) self.assertEqual(im.text, {"TXT": "VALUE", "ZIP": "VALUE"})
def test_roundtrip_itxt(self): def test_roundtrip_itxt(self):
# Check iTXt roundtripping # Check iTXt roundtripping
@ -426,8 +428,7 @@ class TestFilePng(PillowTestCase):
im = Image.new("RGB", (32, 32)) im = Image.new("RGB", (32, 32))
info = PngImagePlugin.PngInfo() info = PngImagePlugin.PngInfo()
info.add_itxt("spam", "Eggs", "en", "Spam") info.add_itxt("spam", "Eggs", "en", "Spam")
info.add_text("eggs", PngImagePlugin.iTXt("Spam", "en", "Eggs"), info.add_text("eggs", PngImagePlugin.iTXt("Spam", "en", "Eggs"), zip=True)
zip=True)
im = roundtrip(im, pnginfo=info) im = roundtrip(im, pnginfo=info)
self.assertEqual(im.info, {"spam": "Eggs", "eggs": "Spam"}) self.assertEqual(im.info, {"spam": "Eggs", "eggs": "Spam"})
@ -459,11 +460,11 @@ class TestFilePng(PillowTestCase):
self.assertEqual(im.info, {"Text": value}) self.assertEqual(im.info, {"Text": value})
if py3: if py3:
rt_text(" Aa" + chr(0xa0) + chr(0xc4) + chr(0xff)) # Latin1 rt_text(" Aa" + chr(0xA0) + chr(0xC4) + chr(0xFF)) # Latin1
rt_text(chr(0x400) + chr(0x472) + chr(0x4ff)) # Cyrillic rt_text(chr(0x400) + chr(0x472) + chr(0x4FF)) # Cyrillic
rt_text(chr(0x4e00) + chr(0x66f0) + # CJK # CJK:
chr(0x9fba) + chr(0x3042) + chr(0xac00)) rt_text(chr(0x4E00) + chr(0x66F0) + chr(0x9FBA) + chr(0x3042) + chr(0xAC00))
rt_text("A" + chr(0xc4) + chr(0x472) + chr(0x3042)) # Combined rt_text("A" + chr(0xC4) + chr(0x472) + chr(0x3042)) # Combined
def test_scary(self): def test_scary(self):
# Check reading of evil PNG file. For information, see: # Check reading of evil PNG file. For information, see:
@ -471,8 +472,8 @@ class TestFilePng(PillowTestCase):
# The first byte is removed from pngtest_bad.png # The first byte is removed from pngtest_bad.png
# to avoid classification as malware. # to avoid classification as malware.
with open("Tests/images/pngtest_bad.png.bin", 'rb') as fd: with open("Tests/images/pngtest_bad.png.bin", "rb") as fd:
data = b'\x89' + fd.read() data = b"\x89" + fd.read()
pngfile = BytesIO(data) pngfile = BytesIO(data)
self.assertRaises(IOError, Image.open, pngfile) self.assertRaises(IOError, Image.open, pngfile)
@ -494,17 +495,16 @@ class TestFilePng(PillowTestCase):
def test_trns_p(self): def test_trns_p(self):
# Check writing a transparency of 0, issue #528 # Check writing a transparency of 0, issue #528
im = hopper('P') im = hopper("P")
im.info['transparency'] = 0 im.info["transparency"] = 0
f = self.tempfile("temp.png") f = self.tempfile("temp.png")
im.save(f) im.save(f)
im2 = Image.open(f) im2 = Image.open(f)
self.assertIn('transparency', im2.info) self.assertIn("transparency", im2.info)
self.assert_image_equal(im2.convert('RGBA'), self.assert_image_equal(im2.convert("RGBA"), im.convert("RGBA"))
im.convert('RGBA'))
def test_trns_null(self): def test_trns_null(self):
# Check reading images with null tRNS value, issue #1239 # Check reading images with null tRNS value, issue #1239
@ -515,39 +515,39 @@ class TestFilePng(PillowTestCase):
def test_save_icc_profile(self): def test_save_icc_profile(self):
im = Image.open("Tests/images/icc_profile_none.png") im = Image.open("Tests/images/icc_profile_none.png")
self.assertIsNone(im.info['icc_profile']) self.assertIsNone(im.info["icc_profile"])
with_icc = Image.open("Tests/images/icc_profile.png") with_icc = Image.open("Tests/images/icc_profile.png")
expected_icc = with_icc.info['icc_profile'] expected_icc = with_icc.info["icc_profile"]
im = roundtrip(im, icc_profile=expected_icc) im = roundtrip(im, icc_profile=expected_icc)
self.assertEqual(im.info['icc_profile'], expected_icc) self.assertEqual(im.info["icc_profile"], expected_icc)
def test_discard_icc_profile(self): def test_discard_icc_profile(self):
im = Image.open('Tests/images/icc_profile.png') im = Image.open("Tests/images/icc_profile.png")
im = roundtrip(im, icc_profile=None) im = roundtrip(im, icc_profile=None)
self.assertNotIn('icc_profile', im.info) self.assertNotIn("icc_profile", im.info)
def test_roundtrip_icc_profile(self): def test_roundtrip_icc_profile(self):
im = Image.open('Tests/images/icc_profile.png') im = Image.open("Tests/images/icc_profile.png")
expected_icc = im.info['icc_profile'] expected_icc = im.info["icc_profile"]
im = roundtrip(im) im = roundtrip(im)
self.assertEqual(im.info['icc_profile'], expected_icc) self.assertEqual(im.info["icc_profile"], expected_icc)
def test_roundtrip_no_icc_profile(self): def test_roundtrip_no_icc_profile(self):
im = Image.open("Tests/images/icc_profile_none.png") im = Image.open("Tests/images/icc_profile_none.png")
self.assertIsNone(im.info['icc_profile']) self.assertIsNone(im.info["icc_profile"])
im = roundtrip(im) im = roundtrip(im)
self.assertNotIn('icc_profile', im.info) self.assertNotIn("icc_profile", im.info)
def test_repr_png(self): def test_repr_png(self):
im = hopper() im = hopper()
repr_png = Image.open(BytesIO(im._repr_png_())) repr_png = Image.open(BytesIO(im._repr_png_()))
self.assertEqual(repr_png.format, 'PNG') self.assertEqual(repr_png.format, "PNG")
self.assert_image_equal(im, repr_png) self.assert_image_equal(im, repr_png)
def test_chunk_order(self): def test_chunk_order(self):
@ -579,10 +579,10 @@ class TestFilePng(PillowTestCase):
def test_textual_chunks_after_idat(self): def test_textual_chunks_after_idat(self):
im = Image.open("Tests/images/hopper.png") im = Image.open("Tests/images/hopper.png")
self.assertIn('comment', im.text.keys()) self.assertIn("comment", im.text.keys())
for k, v in { for k, v in {
'date:create': '2014-09-04T09:37:08+03:00', "date:create": "2014-09-04T09:37:08+03:00",
'date:modify': '2014-09-04T09:37:08+03:00', "date:modify": "2014-09-04T09:37:08+03:00",
}.items(): }.items():
self.assertEqual(im.text[k], v) self.assertEqual(im.text[k], v)
@ -601,7 +601,7 @@ class TestFilePng(PillowTestCase):
# Raises an EOFError in load_end # Raises an EOFError in load_end
im = Image.open("Tests/images/hopper_idat_after_image_end.png") im = Image.open("Tests/images/hopper_idat_after_image_end.png")
self.assertEqual(im.text, {'TXT': 'VALUE', 'ZIP': 'VALUE'}) self.assertEqual(im.text, {"TXT": "VALUE", "ZIP": "VALUE"})
def test_exif(self): def test_exif(self):
im = Image.open("Tests/images/exif.png") im = Image.open("Tests/images/exif.png")
@ -637,20 +637,21 @@ class TestFilePng(PillowTestCase):
reloaded = Image.open(test_file) reloaded = Image.open(test_file)
self.assertEqual(reloaded.info["exif"], b"Exif\x00\x00exifstring") self.assertEqual(reloaded.info["exif"], b"Exif\x00\x00exifstring")
@unittest.skipUnless(HAVE_WEBP and _webp.HAVE_WEBPANIM, @unittest.skipUnless(
"WebP support not installed with animation") HAVE_WEBP and _webp.HAVE_WEBPANIM, "WebP support not installed with animation"
)
def test_apng(self): def test_apng(self):
im = Image.open("Tests/images/iss634.apng") im = Image.open("Tests/images/iss634.apng")
self.assertEqual(im.get_format_mimetype(), 'image/apng') self.assertEqual(im.get_format_mimetype(), "image/apng")
# This also tests reading unknown PNG chunks (fcTL and fdAT) in load_end # This also tests reading unknown PNG chunks (fcTL and fdAT) in load_end
expected = Image.open("Tests/images/iss634.webp") expected = Image.open("Tests/images/iss634.webp")
self.assert_image_similar(im, expected, 0.23) self.assert_image_similar(im, expected, 0.23)
@unittest.skipIf(sys.platform.startswith('win32'), "requires Unix or macOS") @unittest.skipIf(sys.platform.startswith("win32"), "requires Unix or macOS")
class TestTruncatedPngPLeaks(PillowLeakTestCase): class TestTruncatedPngPLeaks(PillowLeakTestCase):
mem_limit = 2*1024 # max increase in K mem_limit = 2 * 1024 # max increase in K
iterations = 100 # Leak is 56k/iteration, this will leak 5.6megs iterations = 100 # Leak is 56k/iteration, this will leak 5.6megs
def setUp(self): def setUp(self):
@ -658,7 +659,7 @@ class TestTruncatedPngPLeaks(PillowLeakTestCase):
self.skipTest("zip/deflate support not available") self.skipTest("zip/deflate support not available")
def test_leak_load(self): def test_leak_load(self):
with open('Tests/images/hopper.png', 'rb') as f: with open("Tests/images/hopper.png", "rb") as f:
DATA = BytesIO(f.read(16 * 1024)) DATA = BytesIO(f.read(16 * 1024))
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True

View File

@ -7,7 +7,6 @@ test_file = "Tests/images/hopper.ppm"
class TestFilePpm(PillowTestCase): class TestFilePpm(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(test_file) im = Image.open(test_file)
im.load() im.load()
@ -17,39 +16,39 @@ class TestFilePpm(PillowTestCase):
self.assertEqual(im.get_format_mimetype(), "image/x-portable-pixmap") self.assertEqual(im.get_format_mimetype(), "image/x-portable-pixmap")
def test_16bit_pgm(self): def test_16bit_pgm(self):
im = Image.open('Tests/images/16_bit_binary.pgm') im = Image.open("Tests/images/16_bit_binary.pgm")
im.load() im.load()
self.assertEqual(im.mode, 'I') self.assertEqual(im.mode, "I")
self.assertEqual(im.size, (20, 100)) self.assertEqual(im.size, (20, 100))
self.assertEqual(im.get_format_mimetype(), "image/x-portable-graymap") self.assertEqual(im.get_format_mimetype(), "image/x-portable-graymap")
tgt = Image.open('Tests/images/16_bit_binary_pgm.png') tgt = Image.open("Tests/images/16_bit_binary_pgm.png")
self.assert_image_equal(im, tgt) self.assert_image_equal(im, tgt)
def test_16bit_pgm_write(self): def test_16bit_pgm_write(self):
im = Image.open('Tests/images/16_bit_binary.pgm') im = Image.open("Tests/images/16_bit_binary.pgm")
im.load() im.load()
f = self.tempfile('temp.pgm') f = self.tempfile("temp.pgm")
im.save(f, 'PPM') im.save(f, "PPM")
reloaded = Image.open(f) reloaded = Image.open(f)
self.assert_image_equal(im, reloaded) self.assert_image_equal(im, reloaded)
def test_pnm(self): def test_pnm(self):
im = Image.open('Tests/images/hopper.pnm') im = Image.open("Tests/images/hopper.pnm")
self.assert_image_similar(im, hopper(), 0.0001) self.assert_image_similar(im, hopper(), 0.0001)
f = self.tempfile('temp.pnm') f = self.tempfile("temp.pnm")
im.save(f) im.save(f)
reloaded = Image.open(f) reloaded = Image.open(f)
self.assert_image_equal(im, reloaded) self.assert_image_equal(im, reloaded)
def test_truncated_file(self): def test_truncated_file(self):
path = self.tempfile('temp.pgm') path = self.tempfile("temp.pgm")
with open(path, 'w') as f: with open(path, "w") as f:
f.write('P6') f.write("P6")
self.assertRaises(ValueError, Image.open, path) self.assertRaises(ValueError, Image.open, path)
@ -60,17 +59,17 @@ class TestFilePpm(PillowTestCase):
# sizes. # sizes.
with self.assertRaises(IOError): with self.assertRaises(IOError):
Image.open('Tests/images/negative_size.ppm') Image.open("Tests/images/negative_size.ppm")
def test_mimetypes(self): def test_mimetypes(self):
path = self.tempfile('temp.pgm') path = self.tempfile("temp.pgm")
with open(path, 'w') as f: with open(path, "w") as f:
f.write("P4\n128 128\n255") f.write("P4\n128 128\n255")
im = Image.open(path) im = Image.open(path)
self.assertEqual(im.get_format_mimetype(), "image/x-portable-bitmap") self.assertEqual(im.get_format_mimetype(), "image/x-portable-bitmap")
with open(path, 'w') as f: with open(path, "w") as f:
f.write("PyCMYK\n128 128\n255") f.write("PyCMYK\n128 128\n255")
im = Image.open(path) im = Image.open(path)
self.assertEqual(im.get_format_mimetype(), "image/x-portable-anymap") self.assertEqual(im.get_format_mimetype(), "image/x-portable-anymap")

View File

@ -6,7 +6,6 @@ test_file = "Tests/images/hopper.psd"
class TestImagePsd(PillowTestCase): class TestImagePsd(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(test_file) im = Image.open(test_file)
im.load() im.load()
@ -20,8 +19,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(SyntaxError, PsdImagePlugin.PsdImageFile, invalid_file)
PsdImagePlugin.PsdImageFile, invalid_file)
def test_n_frames(self): def test_n_frames(self):
im = Image.open("Tests/images/hopper_merged.psd") im = Image.open("Tests/images/hopper_merged.psd")
@ -35,14 +33,14 @@ class TestImagePsd(PillowTestCase):
def test_eoferror(self): def test_eoferror(self):
im = Image.open(test_file) im = Image.open(test_file)
# PSD seek index starts at 1 rather than 0 # PSD seek index starts at 1 rather than 0
n_frames = im.n_frames+1 n_frames = im.n_frames + 1
# Test seeking past the last frame # Test seeking past the last frame
self.assertRaises(EOFError, im.seek, n_frames) self.assertRaises(EOFError, im.seek, n_frames)
self.assertLess(im.tell(), n_frames) self.assertLess(im.tell(), n_frames)
# Test that seeking to the last frame does not raise an error # Test that seeking to the last frame does not raise an error
im.seek(n_frames-1) im.seek(n_frames - 1)
def test_seek_tell(self): def test_seek_tell(self):
im = Image.open(test_file) im = Image.open(test_file)

View File

@ -4,7 +4,6 @@ from PIL import Image, SgiImagePlugin
class TestFileSgi(PillowTestCase): class TestFileSgi(PillowTestCase):
def test_rgb(self): def test_rgb(self):
# Created with ImageMagick then renamed: # Created with ImageMagick then renamed:
# convert hopper.ppm -compress None sgi:hopper.rgb # convert hopper.ppm -compress None sgi:hopper.rgb
@ -12,7 +11,7 @@ class TestFileSgi(PillowTestCase):
im = Image.open(test_file) im = Image.open(test_file)
self.assert_image_equal(im, hopper()) self.assert_image_equal(im, hopper())
self.assertEqual(im.get_format_mimetype(), 'image/rgb') self.assertEqual(im.get_format_mimetype(), "image/rgb")
def test_rgb16(self): def test_rgb16(self):
test_file = "Tests/images/hopper16.rgb" test_file = "Tests/images/hopper16.rgb"
@ -26,8 +25,8 @@ class TestFileSgi(PillowTestCase):
test_file = "Tests/images/hopper.bw" test_file = "Tests/images/hopper.bw"
im = Image.open(test_file) im = Image.open(test_file)
self.assert_image_similar(im, hopper('L'), 2) self.assert_image_similar(im, hopper("L"), 2)
self.assertEqual(im.get_format_mimetype(), 'image/sgi') self.assertEqual(im.get_format_mimetype(), "image/sgi")
def test_rgba(self): def test_rgba(self):
# Created with ImageMagick: # Created with ImageMagick:
@ -35,9 +34,9 @@ class TestFileSgi(PillowTestCase):
test_file = "Tests/images/transparent.sgi" test_file = "Tests/images/transparent.sgi"
im = Image.open(test_file) im = Image.open(test_file)
target = Image.open('Tests/images/transparent.png') target = Image.open("Tests/images/transparent.png")
self.assert_image_equal(im, target) self.assert_image_equal(im, target)
self.assertEqual(im.get_format_mimetype(), 'image/sgi') self.assertEqual(im.get_format_mimetype(), "image/sgi")
def test_rle(self): def test_rle(self):
# Created with ImageMagick: # Created with ImageMagick:
@ -45,47 +44,46 @@ class TestFileSgi(PillowTestCase):
test_file = "Tests/images/hopper.sgi" test_file = "Tests/images/hopper.sgi"
im = Image.open(test_file) im = Image.open(test_file)
target = Image.open('Tests/images/hopper.rgb') target = Image.open("Tests/images/hopper.rgb")
self.assert_image_equal(im, target) self.assert_image_equal(im, target)
def test_rle16(self): def test_rle16(self):
test_file = "Tests/images/tv16.sgi" test_file = "Tests/images/tv16.sgi"
im = Image.open(test_file) im = Image.open(test_file)
target = Image.open('Tests/images/tv.rgb') target = Image.open("Tests/images/tv.rgb")
self.assert_image_equal(im, target) self.assert_image_equal(im, target)
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(ValueError, self.assertRaises(ValueError, SgiImagePlugin.SgiImageFile, invalid_file)
SgiImagePlugin.SgiImageFile, invalid_file)
def test_write(self): def test_write(self):
def roundtrip(img): def roundtrip(img):
out = self.tempfile('temp.sgi') out = self.tempfile("temp.sgi")
img.save(out, format='sgi') img.save(out, format="sgi")
reloaded = Image.open(out) reloaded = Image.open(out)
self.assert_image_equal(img, reloaded) self.assert_image_equal(img, reloaded)
for mode in ('L', 'RGB', 'RGBA'): for mode in ("L", "RGB", "RGBA"):
roundtrip(hopper(mode)) roundtrip(hopper(mode))
# Test 1 dimension for an L mode image # Test 1 dimension for an L mode image
roundtrip(Image.new('L', (10, 1))) roundtrip(Image.new("L", (10, 1)))
def test_write16(self): def test_write16(self):
test_file = "Tests/images/hopper16.rgb" test_file = "Tests/images/hopper16.rgb"
im = Image.open(test_file) im = Image.open(test_file)
out = self.tempfile('temp.sgi') out = self.tempfile("temp.sgi")
im.save(out, format='sgi', bpc=2) im.save(out, format="sgi", bpc=2)
reloaded = Image.open(out) reloaded = Image.open(out)
self.assert_image_equal(im, reloaded) self.assert_image_equal(im, reloaded)
def test_unsupported_mode(self): def test_unsupported_mode(self):
im = hopper('LA') im = hopper("LA")
out = self.tempfile('temp.sgi') out = self.tempfile("temp.sgi")
self.assertRaises(ValueError, im.save, out, format='sgi') self.assertRaises(ValueError, im.save, out, format="sgi")

View File

@ -10,7 +10,6 @@ TEST_FILE = "Tests/images/hopper.spider"
class TestImageSpider(PillowTestCase): class TestImageSpider(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
im.load() im.load()
@ -22,11 +21,12 @@ class TestImageSpider(PillowTestCase):
def open(): def open():
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
im.load() im.load()
self.assert_warning(None, open) self.assert_warning(None, open)
def test_save(self): def test_save(self):
# Arrange # Arrange
temp = self.tempfile('temp.spider') temp = self.tempfile("temp.spider")
im = hopper() im = hopper()
# Act # Act

View File

@ -4,11 +4,10 @@ from PIL import Image, SunImagePlugin
import os import os
EXTRA_DIR = 'Tests/images/sunraster' EXTRA_DIR = "Tests/images/sunraster"
class TestFileSun(PillowTestCase): class TestFileSun(PillowTestCase):
def test_sanity(self): def test_sanity(self):
# Arrange # Arrange
# Created with ImageMagick: convert hopper.jpg hopper.ras # Created with ImageMagick: convert hopper.jpg hopper.ras
@ -23,20 +22,20 @@ class TestFileSun(PillowTestCase):
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(SyntaxError, SunImagePlugin.SunImageFile, invalid_file)
SunImagePlugin.SunImageFile, invalid_file)
def test_im1(self): def test_im1(self):
im = Image.open('Tests/images/sunraster.im1') im = Image.open("Tests/images/sunraster.im1")
target = Image.open('Tests/images/sunraster.im1.png') target = Image.open("Tests/images/sunraster.im1.png")
self.assert_image_equal(im, target) self.assert_image_equal(im, target)
@unittest.skipIf(not os.path.exists(EXTRA_DIR), @unittest.skipIf(not os.path.exists(EXTRA_DIR), "Extra image files not installed")
"Extra image files not installed")
def test_others(self): def test_others(self):
files = (os.path.join(EXTRA_DIR, f) for f in files = (
os.listdir(EXTRA_DIR) if os.path.splitext(f)[1] os.path.join(EXTRA_DIR, f)
in ('.sun', '.SUN', '.ras')) for f in os.listdir(EXTRA_DIR)
if os.path.splitext(f)[1] 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()

View File

@ -9,15 +9,14 @@ TEST_TAR_FILE = "Tests/images/hopper.tar"
class TestFileTar(PillowTestCase): class TestFileTar(PillowTestCase):
def setUp(self): def setUp(self):
if "zip_decoder" not in codecs and "jpeg_decoder" not in codecs: if "zip_decoder" not in codecs and "jpeg_decoder" not in codecs:
self.skipTest("neither jpeg nor zip support available") self.skipTest("neither jpeg nor zip support available")
def test_sanity(self): def test_sanity(self):
for codec, test_path, format in [ for codec, test_path, format in [
['zip_decoder', 'hopper.png', 'PNG'], ["zip_decoder", "hopper.png", "PNG"],
['jpeg_decoder', 'hopper.jpg', 'JPEG'] ["jpeg_decoder", "hopper.jpg", "JPEG"],
]: ]:
if codec in codecs: if codec in codecs:
tar = TarIO.TarIO(TEST_TAR_FILE, test_path) tar = TarIO.TarIO(TEST_TAR_FILE, test_path)
@ -28,9 +27,9 @@ class TestFileTar(PillowTestCase):
self.assertEqual(im.format, format) self.assertEqual(im.format, format)
def test_close(self): def test_close(self):
tar = TarIO.TarIO(TEST_TAR_FILE, 'hopper.jpg') tar = TarIO.TarIO(TEST_TAR_FILE, "hopper.jpg")
tar.close() tar.close()
def test_contextmanager(self): def test_contextmanager(self):
with TarIO.TarIO(TEST_TAR_FILE, 'hopper.jpg'): with TarIO.TarIO(TEST_TAR_FILE, "hopper.jpg"):
pass pass

View File

@ -16,16 +16,13 @@ class TestFileTga(PillowTestCase):
_MODES = ("L", "LA", "P", "RGB", "RGBA") _MODES = ("L", "LA", "P", "RGB", "RGBA")
_ORIGINS = ("tl", "bl") _ORIGINS = ("tl", "bl")
_ORIGIN_TO_ORIENTATION = { _ORIGIN_TO_ORIENTATION = {"tl": 1, "bl": -1}
"tl": 1,
"bl": -1
}
def test_sanity(self): def test_sanity(self):
for mode in self._MODES: for mode in self._MODES:
png_paths = glob( png_paths = glob(
os.path.join( os.path.join(_TGA_DIR_COMMON, "*x*_{}.png".format(mode.lower()))
_TGA_DIR_COMMON, "*x*_{}.png".format(mode.lower()))) )
for png_path in png_paths: for png_path in png_paths:
reference_im = Image.open(png_path) reference_im = Image.open(png_path)
@ -34,21 +31,22 @@ class TestFileTga(PillowTestCase):
path_no_ext = os.path.splitext(png_path)[0] path_no_ext = os.path.splitext(png_path)[0]
for origin, rle in product(self._ORIGINS, (True, False)): for origin, rle in product(self._ORIGINS, (True, False)):
tga_path = "{}_{}_{}.tga".format( tga_path = "{}_{}_{}.tga".format(
path_no_ext, origin, "rle" if rle else "raw") path_no_ext, origin, "rle" if rle else "raw"
)
original_im = Image.open(tga_path) original_im = Image.open(tga_path)
self.assertEqual(original_im.format, "TGA") self.assertEqual(original_im.format, "TGA")
self.assertEqual(original_im.get_format_mimetype(), "image/x-tga") self.assertEqual(original_im.get_format_mimetype(), "image/x-tga")
if rle: if rle:
self.assertEqual( self.assertEqual(original_im.info["compression"], "tga_rle")
original_im.info["compression"], "tga_rle")
self.assertEqual( self.assertEqual(
original_im.info["orientation"], original_im.info["orientation"],
self._ORIGIN_TO_ORIENTATION[origin]) self._ORIGIN_TO_ORIENTATION[origin],
)
if mode == "P": if mode == "P":
self.assertEqual( self.assertEqual(
original_im.getpalette(), original_im.getpalette(), reference_im.getpalette()
reference_im.getpalette()) )
self.assert_image_equal(original_im, reference_im) self.assert_image_equal(original_im, reference_im)
@ -62,14 +60,15 @@ class TestFileTga(PillowTestCase):
if rle: if rle:
self.assertEqual( self.assertEqual(
saved_im.info["compression"], saved_im.info["compression"],
original_im.info["compression"]) original_im.info["compression"],
)
self.assertEqual( self.assertEqual(
saved_im.info["orientation"], saved_im.info["orientation"], original_im.info["orientation"]
original_im.info["orientation"]) )
if mode == "P": if mode == "P":
self.assertEqual( self.assertEqual(
saved_im.getpalette(), saved_im.getpalette(), original_im.getpalette()
original_im.getpalette()) )
self.assert_image_equal(saved_im, original_im) self.assert_image_equal(saved_im, original_im)
@ -128,8 +127,7 @@ class TestFileTga(PillowTestCase):
# Save with custom id section greater than 255 characters # Save with custom id section greater than 255 characters
id_section = b"Test content" * 25 id_section = b"Test content" * 25
self.assert_warning(UserWarning, self.assert_warning(UserWarning, lambda: im.save(out, id_section=id_section))
lambda: im.save(out, id_section=id_section))
test_im = Image.open(out) test_im = Image.open(out)
self.assertEqual(test_im.info["id_section"], id_section[:255]) self.assertEqual(test_im.info["id_section"], id_section[:255])
@ -191,15 +189,13 @@ class TestFileTga(PillowTestCase):
in_file = "Tests/images/la.tga" in_file = "Tests/images/la.tga"
im = Image.open(in_file) im = Image.open(in_file)
self.assertEqual(im.mode, "LA") self.assertEqual(im.mode, "LA")
self.assertEqual( self.assertEqual(im.getchannel("A").getcolors()[0][0], num_transparent)
im.getchannel("A").getcolors()[0][0], num_transparent)
out = self.tempfile("temp.tga") out = self.tempfile("temp.tga")
im.save(out) im.save(out)
test_im = Image.open(out) test_im = Image.open(out)
self.assertEqual(test_im.mode, "LA") self.assertEqual(test_im.mode, "LA")
self.assertEqual( self.assertEqual(test_im.getchannel("A").getcolors()[0][0], num_transparent)
test_im.getchannel("A").getcolors()[0][0], num_transparent)
self.assert_image_equal(im, test_im) self.assert_image_equal(im, test_im)

View File

@ -12,7 +12,6 @@ logger = logging.getLogger(__name__)
class TestFileTiff(PillowTestCase): class TestFileTiff(PillowTestCase):
def test_sanity(self): def test_sanity(self):
filename = self.tempfile("temp.tif") filename = self.tempfile("temp.tif")
@ -44,6 +43,7 @@ class TestFileTiff(PillowTestCase):
def open(): def open():
im = Image.open("Tests/images/multipage.tiff") im = Image.open("Tests/images/multipage.tiff")
im.load() im.load()
self.assert_warning(None, open) self.assert_warning(None, open)
def test_mac_tiff(self): def test_mac_tiff(self):
@ -54,7 +54,7 @@ class TestFileTiff(PillowTestCase):
self.assertEqual(im.mode, "RGBA") self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (55, 43)) self.assertEqual(im.size, (55, 43))
self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))]) self.assertEqual(im.tile, [("raw", (0, 0, 55, 43), 8, ("RGBa", 0, 1))])
im.load() im.load()
self.assert_image_similar_tofile(im, "Tests/images/pil136.png", 1) self.assert_image_similar_tofile(im, "Tests/images/pil136.png", 1)
@ -64,16 +64,14 @@ class TestFileTiff(PillowTestCase):
self.assertEqual(im.mode, "RGBA") self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (52, 53)) self.assertEqual(im.size, (52, 53))
self.assertEqual(im.tile, self.assertEqual(im.tile, [("raw", (0, 0, 52, 53), 160, ("RGBA", 0, 1))])
[('raw', (0, 0, 52, 53), 160, ('RGBA', 0, 1))])
im.load() im.load()
def test_set_legacy_api(self): def test_set_legacy_api(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
with self.assertRaises(Exception) as e: with self.assertRaises(Exception) as e:
ifd.legacy_api = None ifd.legacy_api = None
self.assertEqual(str(e.exception), self.assertEqual(str(e.exception), "Not allowing setting of legacy api")
"Not allowing setting of legacy api")
def test_size(self): def test_size(self):
filename = "Tests/images/pil168.tif" filename = "Tests/images/pil168.tif"
@ -81,6 +79,7 @@ class TestFileTiff(PillowTestCase):
def set_size(): def set_size():
im.size = (256, 256) im.size = (256, 256)
self.assert_warning(DeprecationWarning, set_size) self.assert_warning(DeprecationWarning, set_size)
def test_xyres_tiff(self): def test_xyres_tiff(self):
@ -92,29 +91,24 @@ class TestFileTiff(PillowTestCase):
self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple) self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)
# v2 api # v2 api
self.assertIsInstance(im.tag_v2[X_RESOLUTION], self.assertIsInstance(im.tag_v2[X_RESOLUTION], TiffImagePlugin.IFDRational)
TiffImagePlugin.IFDRational) self.assertIsInstance(im.tag_v2[Y_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[Y_RESOLUTION],
TiffImagePlugin.IFDRational)
self.assertEqual(im.info['dpi'], (72., 72.)) self.assertEqual(im.info["dpi"], (72.0, 72.0))
def test_xyres_fallback_tiff(self): def test_xyres_fallback_tiff(self):
filename = "Tests/images/compression.tif" filename = "Tests/images/compression.tif"
im = Image.open(filename) im = Image.open(filename)
# v2 api # v2 api
self.assertIsInstance(im.tag_v2[X_RESOLUTION], self.assertIsInstance(im.tag_v2[X_RESOLUTION], TiffImagePlugin.IFDRational)
TiffImagePlugin.IFDRational) self.assertIsInstance(im.tag_v2[Y_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[Y_RESOLUTION], self.assertRaises(KeyError, lambda: im.tag_v2[RESOLUTION_UNIT])
TiffImagePlugin.IFDRational)
self.assertRaises(KeyError,
lambda: im.tag_v2[RESOLUTION_UNIT])
# Legacy. # Legacy.
self.assertEqual(im.info['resolution'], (100., 100.)) self.assertEqual(im.info["resolution"], (100.0, 100.0))
# Fallback "inch". # Fallback "inch".
self.assertEqual(im.info['dpi'], (100., 100.)) self.assertEqual(im.info["dpi"], (100.0, 100.0))
def test_int_resolution(self): def test_int_resolution(self):
filename = "Tests/images/pil168.tif" filename = "Tests/images/pil168.tif"
@ -124,20 +118,21 @@ class TestFileTiff(PillowTestCase):
im.tag_v2[X_RESOLUTION] = 71 im.tag_v2[X_RESOLUTION] = 71
im.tag_v2[Y_RESOLUTION] = 71 im.tag_v2[Y_RESOLUTION] = 71
im._setup() im._setup()
self.assertEqual(im.info['dpi'], (71., 71.)) self.assertEqual(im.info["dpi"], (71.0, 71.0))
def test_load_dpi_rounding(self): def test_load_dpi_rounding(self):
for resolutionUnit, dpi in ((None, (72, 73)), for resolutionUnit, dpi in ((None, (72, 73)), (2, (72, 73)), (3, (183, 185))):
(2, (72, 73)),
(3, (183, 185))):
im = Image.open( im = Image.open(
"Tests/images/hopper_roundDown_"+str(resolutionUnit)+".tif") "Tests/images/hopper_roundDown_" + str(resolutionUnit) + ".tif"
)
self.assertEqual(im.tag_v2.get(RESOLUTION_UNIT), resolutionUnit) self.assertEqual(im.tag_v2.get(RESOLUTION_UNIT), resolutionUnit)
self.assertEqual(im.info['dpi'], (dpi[0], dpi[0])) self.assertEqual(im.info["dpi"], (dpi[0], dpi[0]))
im = Image.open("Tests/images/hopper_roundUp_"+str(resolutionUnit)+".tif") im = Image.open(
"Tests/images/hopper_roundUp_" + str(resolutionUnit) + ".tif"
)
self.assertEqual(im.tag_v2.get(RESOLUTION_UNIT), resolutionUnit) self.assertEqual(im.tag_v2.get(RESOLUTION_UNIT), resolutionUnit)
self.assertEqual(im.info['dpi'], (dpi[1], dpi[1])) self.assertEqual(im.info["dpi"], (dpi[1], dpi[1]))
def test_save_dpi_rounding(self): def test_save_dpi_rounding(self):
outfile = self.tempfile("temp.tif") outfile = self.tempfile("temp.tif")
@ -148,12 +143,13 @@ class TestFileTiff(PillowTestCase):
reloaded = Image.open(outfile) reloaded = Image.open(outfile)
reloaded.load() reloaded.load()
self.assertEqual((round(dpi), round(dpi)), reloaded.info['dpi']) self.assertEqual((round(dpi), round(dpi)), reloaded.info["dpi"])
def test_save_setting_missing_resolution(self): def test_save_setting_missing_resolution(self):
b = BytesIO() b = BytesIO()
Image.open("Tests/images/10ct_32bit_128.tiff").save( Image.open("Tests/images/10ct_32bit_128.tiff").save(
b, format="tiff", resolution=123.45) b, format="tiff", resolution=123.45
)
im = Image.open(b) im = Image.open(b)
self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45) self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45)
self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45) self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45)
@ -161,16 +157,14 @@ 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(SyntaxError, TiffImagePlugin.TiffImageFile, invalid_file)
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(SyntaxError, TiffImagePlugin.TiffImageFile, invalid_file)
TiffImagePlugin.TiffImageFile, invalid_file)
TiffImagePlugin.PREFIXES.pop() TiffImagePlugin.PREFIXES.pop()
def test_bad_exif(self): def test_bad_exif(self):
i = Image.open('Tests/images/hopper_bad_exif.jpg') i = Image.open("Tests/images/hopper_bad_exif.jpg")
# Should not raise struct.error. # Should not raise struct.error.
self.assert_warning(UserWarning, i._getexif) self.assert_warning(UserWarning, i._getexif)
@ -185,38 +179,38 @@ class TestFileTiff(PillowTestCase):
self.assertRaises(IOError, im.save, outfile) self.assertRaises(IOError, im.save, outfile)
def test_little_endian(self): def test_little_endian(self):
im = Image.open('Tests/images/16bit.cropped.tif') im = Image.open("Tests/images/16bit.cropped.tif")
self.assertEqual(im.getpixel((0, 0)), 480) self.assertEqual(im.getpixel((0, 0)), 480)
self.assertEqual(im.mode, 'I;16') self.assertEqual(im.mode, "I;16")
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (little endian) # Bytes are in image native order (little endian)
if py3: if py3:
self.assertEqual(b[0], ord(b'\xe0')) self.assertEqual(b[0], ord(b"\xe0"))
self.assertEqual(b[1], ord(b'\x01')) self.assertEqual(b[1], ord(b"\x01"))
else: else:
self.assertEqual(b[0], b'\xe0') self.assertEqual(b[0], b"\xe0")
self.assertEqual(b[1], b'\x01') self.assertEqual(b[1], b"\x01")
def test_big_endian(self): def test_big_endian(self):
im = Image.open('Tests/images/16bit.MM.cropped.tif') im = Image.open("Tests/images/16bit.MM.cropped.tif")
self.assertEqual(im.getpixel((0, 0)), 480) self.assertEqual(im.getpixel((0, 0)), 480)
self.assertEqual(im.mode, 'I;16B') self.assertEqual(im.mode, "I;16B")
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (big endian) # Bytes are in image native order (big endian)
if py3: if py3:
self.assertEqual(b[0], ord(b'\x01')) self.assertEqual(b[0], ord(b"\x01"))
self.assertEqual(b[1], ord(b'\xe0')) self.assertEqual(b[1], ord(b"\xe0"))
else: else:
self.assertEqual(b[0], b'\x01') self.assertEqual(b[0], b"\x01")
self.assertEqual(b[1], b'\xe0') self.assertEqual(b[1], b"\xe0")
def test_16bit_s(self): def test_16bit_s(self):
im = Image.open('Tests/images/16bit.s.tif') im = Image.open("Tests/images/16bit.s.tif")
im.load() im.load()
self.assertEqual(im.mode, 'I') self.assertEqual(im.mode, "I")
self.assertEqual(im.getpixel((0, 0)), 32767) self.assertEqual(im.getpixel((0, 0)), 32767)
self.assertEqual(im.getpixel((0, 1)), 0) self.assertEqual(im.getpixel((0, 1)), 0)
@ -224,7 +218,7 @@ class TestFileTiff(PillowTestCase):
""" Are we generating the same interpretation """ Are we generating the same interpretation
of the image as Imagemagick is? """ of the image as Imagemagick is? """
im = Image.open('Tests/images/12bit.cropped.tif') im = Image.open("Tests/images/12bit.cropped.tif")
# to make the target -- # to make the target --
# convert 12bit.cropped.tif -depth 16 tmp.tif # convert 12bit.cropped.tif -depth 16 tmp.tif
@ -232,33 +226,33 @@ class TestFileTiff(PillowTestCase):
# imagemagick will auto scale so that a 12bit FFF is 16bit FFF0, # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,
# so we need to unshift so that the integer values are the same. # so we need to unshift so that the integer values are the same.
self.assert_image_equal_tofile(im, 'Tests/images/12in16bit.tif') self.assert_image_equal_tofile(im, "Tests/images/12in16bit.tif")
def test_32bit_float(self): def test_32bit_float(self):
# Issue 614, specific 32-bit float format # Issue 614, specific 32-bit float format
path = 'Tests/images/10ct_32bit_128.tiff' path = "Tests/images/10ct_32bit_128.tiff"
im = Image.open(path) im = Image.open(path)
im.load() im.load()
self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343) self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)
self.assertEqual( self.assertEqual(im.getextrema(), (-3.140936851501465, 3.140684127807617))
im.getextrema(), (-3.140936851501465, 3.140684127807617))
def test_unknown_pixel_mode(self): def test_unknown_pixel_mode(self):
self.assertRaises( self.assertRaises(
IOError, Image.open, 'Tests/images/hopper_unknown_pixel_mode.tif') IOError, Image.open, "Tests/images/hopper_unknown_pixel_mode.tif"
)
def test_n_frames(self): def test_n_frames(self):
for path, n_frames in [ for path, n_frames in [
['Tests/images/multipage-lastframe.tif', 1], ["Tests/images/multipage-lastframe.tif", 1],
['Tests/images/multipage.tiff', 3] ["Tests/images/multipage.tiff", 3],
]: ]:
im = Image.open(path) im = Image.open(path)
self.assertEqual(im.n_frames, n_frames) self.assertEqual(im.n_frames, n_frames)
self.assertEqual(im.is_animated, n_frames != 1) self.assertEqual(im.is_animated, n_frames != 1)
def test_eoferror(self): def test_eoferror(self):
im = Image.open('Tests/images/multipage-lastframe.tif') im = Image.open("Tests/images/multipage-lastframe.tif")
n_frames = im.n_frames n_frames = im.n_frames
# Test seeking past the last frame # Test seeking past the last frame
@ -266,37 +260,37 @@ class TestFileTiff(PillowTestCase):
self.assertLess(im.tell(), n_frames) self.assertLess(im.tell(), n_frames)
# Test that seeking to the last frame does not raise an error # Test that seeking to the last frame does not raise an error
im.seek(n_frames-1) im.seek(n_frames - 1)
def test_multipage(self): def test_multipage(self):
# issue #862 # issue #862
im = Image.open('Tests/images/multipage.tiff') im = Image.open("Tests/images/multipage.tiff")
# file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue
im.seek(0) im.seek(0)
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 128, 0))
im.seek(1) im.seek(1)
im.load() im.load()
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (255, 0, 0))
im.seek(0) im.seek(0)
im.load() im.load()
self.assertEqual(im.size, (10, 10)) self.assertEqual(im.size, (10, 10))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 128, 0))
im.seek(2) im.seek(2)
im.load() im.load()
self.assertEqual(im.size, (20, 20)) self.assertEqual(im.size, (20, 20))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 0, 255))
def test_multipage_last_frame(self): def test_multipage_last_frame(self):
im = Image.open('Tests/images/multipage-lastframe.tif') im = Image.open("Tests/images/multipage-lastframe.tif")
im.load() im.load()
self.assertEqual(im.size, (20, 20)) self.assertEqual(im.size, (20, 20))
self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255)) self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 0, 255))
def test___str__(self): def test___str__(self):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
@ -314,16 +308,39 @@ class TestFileTiff(PillowTestCase):
im = Image.open(filename) im = Image.open(filename)
# v2 interface # v2 interface
v2_tags = {256: 55, 257: 43, 258: (8, 8, 8, 8), 259: 1, v2_tags = {
262: 2, 296: 2, 273: (8,), 338: (1,), 277: 4, 256: 55,
279: (9460,), 282: 72.0, 283: 72.0, 284: 1} 257: 43,
258: (8, 8, 8, 8),
259: 1,
262: 2,
296: 2,
273: (8,),
338: (1,),
277: 4,
279: (9460,),
282: 72.0,
283: 72.0,
284: 1,
}
self.assertEqual(dict(im.tag_v2), v2_tags) self.assertEqual(dict(im.tag_v2), v2_tags)
# legacy interface # legacy interface
legacy_tags = {256: (55,), 257: (43,), 258: (8, 8, 8, 8), 259: (1,), legacy_tags = {
262: (2,), 296: (2,), 273: (8,), 338: (1,), 277: (4,), 256: (55,),
279: (9460,), 282: ((720000, 10000),), 257: (43,),
283: ((720000, 10000),), 284: (1,)} 258: (8, 8, 8, 8),
259: (1,),
262: (2,),
296: (2,),
273: (8,),
338: (1,),
277: (4,),
279: (9460,),
282: ((720000, 10000),),
283: ((720000, 10000),),
284: (1,),
}
self.assertEqual(dict(im.tag), legacy_tags) self.assertEqual(dict(im.tag), legacy_tags)
def test__delitem__(self): def test__delitem__(self):
@ -351,13 +368,13 @@ class TestFileTiff(PillowTestCase):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abcdabcd" data = b"abcdabcd"
ret = ifd.load_float(data, False) ret = ifd.load_float(data, False)
self.assertEqual(ret, (1.6777999408082104e+22, 1.6777999408082104e+22)) self.assertEqual(ret, (1.6777999408082104e22, 1.6777999408082104e22))
def test_load_double(self): def test_load_double(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abcdefghabcdefgh" data = b"abcdefghabcdefgh"
ret = ifd.load_double(data, False) ret = ifd.load_double(data, False)
self.assertEqual(ret, (8.540883223036124e+194, 8.540883223036124e+194)) self.assertEqual(ret, (8.540883223036124e194, 8.540883223036124e194))
def test_seek(self): def test_seek(self):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
@ -374,12 +391,14 @@ class TestFileTiff(PillowTestCase):
def test__limit_rational_int(self): def test__limit_rational_int(self):
from PIL.TiffImagePlugin import _limit_rational from PIL.TiffImagePlugin import _limit_rational
value = 34 value = 34
ret = _limit_rational(value, 65536) ret = _limit_rational(value, 65536)
self.assertEqual(ret, (34, 1)) self.assertEqual(ret, (34, 1))
def test__limit_rational_float(self): def test__limit_rational_float(self):
from PIL.TiffImagePlugin import _limit_rational from PIL.TiffImagePlugin import _limit_rational
value = 22.3 value = 22.3
ret = _limit_rational(value, 65536) ret = _limit_rational(value, 65536)
self.assertEqual(ret, (223, 10)) self.assertEqual(ret, (223, 10))
@ -401,7 +420,7 @@ class TestFileTiff(PillowTestCase):
"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2I.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2R.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif",
) ),
), ),
( (
7.3, # epsilon 7.3, # epsilon
@ -410,7 +429,7 @@ class TestFileTiff(PillowTestCase):
"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4I.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4R.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif",
) ),
), ),
) )
original = hopper("L") original = hopper("L")
@ -426,9 +445,7 @@ class TestFileTiff(PillowTestCase):
self.assert_image_equal(im, im2) self.assert_image_equal(im, im2)
def test_with_underscores(self): def test_with_underscores(self):
kwargs = {'resolution_unit': 'inch', kwargs = {"resolution_unit": "inch", "x_resolution": 72, "y_resolution": 36}
'x_resolution': 72,
'y_resolution': 36}
filename = self.tempfile("temp.tif") filename = self.tempfile("temp.tif")
hopper("RGB").save(filename, **kwargs) hopper("RGB").save(filename, **kwargs)
im = Image.open(filename) im = Image.open(filename)
@ -459,8 +476,7 @@ class TestFileTiff(PillowTestCase):
infile = "Tests/images/tiff_strip_raw.tif" infile = "Tests/images/tiff_strip_raw.tif"
im = Image.open(infile) im = Image.open(infile)
self.assert_image_equal_tofile(im, self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
"Tests/images/tiff_adobe_deflate.png")
def test_strip_planar_raw(self): def test_strip_planar_raw(self):
# gdal_translate -of GTiff -co INTERLEAVE=BAND \ # gdal_translate -of GTiff -co INTERLEAVE=BAND \
@ -468,16 +484,14 @@ class TestFileTiff(PillowTestCase):
infile = "Tests/images/tiff_strip_planar_raw.tif" infile = "Tests/images/tiff_strip_planar_raw.tif"
im = Image.open(infile) im = Image.open(infile)
self.assert_image_equal_tofile(im, self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
"Tests/images/tiff_adobe_deflate.png")
def test_strip_planar_raw_with_overviews(self): def test_strip_planar_raw_with_overviews(self):
# gdaladdo tiff_strip_planar_raw2.tif 2 4 8 16 # gdaladdo tiff_strip_planar_raw2.tif 2 4 8 16
infile = "Tests/images/tiff_strip_planar_raw_with_overviews.tif" infile = "Tests/images/tiff_strip_planar_raw_with_overviews.tif"
im = Image.open(infile) im = Image.open(infile)
self.assert_image_equal_tofile(im, self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
"Tests/images/tiff_adobe_deflate.png")
def test_tiled_planar_raw(self): def test_tiled_planar_raw(self):
# gdal_translate -of GTiff -co TILED=YES -co BLOCKXSIZE=32 \ # gdal_translate -of GTiff -co TILED=YES -co BLOCKXSIZE=32 \
@ -486,8 +500,7 @@ class TestFileTiff(PillowTestCase):
infile = "Tests/images/tiff_tiled_planar_raw.tif" infile = "Tests/images/tiff_tiled_planar_raw.tif"
im = Image.open(infile) im = Image.open(infile)
self.assert_image_equal_tofile(im, self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
"Tests/images/tiff_adobe_deflate.png")
def test_palette(self): def test_palette(self):
for mode in ["P", "PA"]: for mode in ["P", "PA"]:
@ -513,9 +526,8 @@ class TestFileTiff(PillowTestCase):
# Test appending images # Test appending images
mp = io.BytesIO() mp = io.BytesIO()
im = Image.new('RGB', (100, 100), '#f00') im = Image.new("RGB", (100, 100), "#f00")
ims = [Image.new('RGB', (100, 100), color) for color ims = [Image.new("RGB", (100, 100), color) for color in ["#0f0", "#00f"]]
in ['#0f0', '#00f']]
im.copy().save(mp, format="TIFF", save_all=True, append_images=ims) im.copy().save(mp, format="TIFF", save_all=True, append_images=ims)
mp.seek(0, os.SEEK_SET) mp.seek(0, os.SEEK_SET)
@ -526,9 +538,9 @@ class TestFileTiff(PillowTestCase):
def imGenerator(ims): def imGenerator(ims):
for im in ims: for im in ims:
yield im yield im
mp = io.BytesIO() mp = io.BytesIO()
im.save(mp, format="TIFF", save_all=True, im.save(mp, format="TIFF", save_all=True, append_images=imGenerator(ims))
append_images=imGenerator(ims))
mp.seek(0, os.SEEK_SET) mp.seek(0, os.SEEK_SET)
reread = Image.open(mp) reread = Image.open(mp)
@ -539,15 +551,15 @@ class TestFileTiff(PillowTestCase):
# At the time of writing this will only work for non-compressed tiffs # At the time of writing this will only work for non-compressed tiffs
# as libtiff does not support embedded ICC profiles, # as libtiff does not support embedded ICC profiles,
# ImageFile._save(..) however does. # ImageFile._save(..) 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"])
def test_close_on_load_exclusive(self): def test_close_on_load_exclusive(self):
# similar to test_fd_leak, but runs on unixlike os # similar to test_fd_leak, but runs on unixlike os
@ -568,7 +580,7 @@ class TestFileTiff(PillowTestCase):
with Image.open("Tests/images/uint16_1_4660.tif") as im: with Image.open("Tests/images/uint16_1_4660.tif") as im:
im.save(tmpfile) im.save(tmpfile)
with open(tmpfile, 'rb') as f: with open(tmpfile, "rb") as f:
im = Image.open(f) im = Image.open(f)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) self.assertFalse(fp.closed)
@ -576,7 +588,7 @@ class TestFileTiff(PillowTestCase):
self.assertFalse(fp.closed) self.assertFalse(fp.closed)
@unittest.skipUnless(sys.platform.startswith('win32'), "Windows only") @unittest.skipUnless(sys.platform.startswith("win32"), "Windows only")
class TestFileTiffW32(PillowTestCase): class TestFileTiffW32(PillowTestCase):
def test_fd_leak(self): def test_fd_leak(self):
tmpfile = self.tempfile("temp.tif") tmpfile = self.tempfile("temp.tif")

View File

@ -10,7 +10,6 @@ tag_ids = {info.name: info.value for info in TiffTags.TAGS_V2.values()}
class TestFileTiffMetadata(PillowTestCase): class TestFileTiffMetadata(PillowTestCase):
def test_rt_metadata(self): def test_rt_metadata(self):
""" Test writing arbitrary metadata into the tiff image directory """ Test writing arbitrary metadata into the tiff image directory
Use case is ImageJ private tags, one numeric, one arbitrary Use case is ImageJ private tags, one numeric, one arbitrary
@ -29,23 +28,23 @@ class TestFileTiffMetadata(PillowTestCase):
# the tiff file format can't take 8 bit bytes in that field. # the tiff file format can't take 8 bit bytes in that field.
basetextdata = "This is some arbitrary metadata for a text field" basetextdata = "This is some arbitrary metadata for a text field"
bindata = basetextdata.encode('ascii') + b" \xff" bindata = basetextdata.encode("ascii") + b" \xff"
textdata = basetextdata + " " + chr(255) textdata = basetextdata + " " + chr(255)
reloaded_textdata = basetextdata + " ?" reloaded_textdata = basetextdata + " ?"
floatdata = 12.345 floatdata = 12.345
doubledata = 67.89 doubledata = 67.89
info = TiffImagePlugin.ImageFileDirectory() info = TiffImagePlugin.ImageFileDirectory()
ImageJMetaData = tag_ids['ImageJMetaData'] ImageJMetaData = tag_ids["ImageJMetaData"]
ImageJMetaDataByteCounts = tag_ids['ImageJMetaDataByteCounts'] ImageJMetaDataByteCounts = tag_ids["ImageJMetaDataByteCounts"]
ImageDescription = tag_ids['ImageDescription'] ImageDescription = tag_ids["ImageDescription"]
info[ImageJMetaDataByteCounts] = len(bindata) info[ImageJMetaDataByteCounts] = len(bindata)
info[ImageJMetaData] = bindata info[ImageJMetaData] = bindata
info[tag_ids['RollAngle']] = floatdata info[tag_ids["RollAngle"]] = floatdata
info.tagtype[tag_ids['RollAngle']] = 11 info.tagtype[tag_ids["RollAngle"]] = 11
info[tag_ids['YawAngle']] = doubledata info[tag_ids["YawAngle"]] = doubledata
info.tagtype[tag_ids['YawAngle']] = 12 info.tagtype[tag_ids["YawAngle"]] = 12
info[ImageDescription] = textdata info[ImageDescription] = textdata
@ -56,8 +55,7 @@ class TestFileTiffMetadata(PillowTestCase):
loaded = Image.open(f) loaded = Image.open(f)
self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (len(bindata),)) self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (len(bindata),))
self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (len(bindata),))
(len(bindata),))
self.assertEqual(loaded.tag[ImageJMetaData], bindata) self.assertEqual(loaded.tag[ImageJMetaData], bindata)
self.assertEqual(loaded.tag_v2[ImageJMetaData], bindata) self.assertEqual(loaded.tag_v2[ImageJMetaData], bindata)
@ -65,9 +63,9 @@ class TestFileTiffMetadata(PillowTestCase):
self.assertEqual(loaded.tag[ImageDescription], (reloaded_textdata,)) self.assertEqual(loaded.tag[ImageDescription], (reloaded_textdata,))
self.assertEqual(loaded.tag_v2[ImageDescription], reloaded_textdata) self.assertEqual(loaded.tag_v2[ImageDescription], reloaded_textdata)
loaded_float = loaded.tag[tag_ids['RollAngle']][0] loaded_float = loaded.tag[tag_ids["RollAngle"]][0]
self.assertAlmostEqual(loaded_float, floatdata, places=5) self.assertAlmostEqual(loaded_float, floatdata, places=5)
loaded_double = loaded.tag[tag_ids['YawAngle']][0] loaded_double = loaded.tag[tag_ids["YawAngle"]][0]
self.assertAlmostEqual(loaded_double, doubledata) self.assertAlmostEqual(loaded_double, doubledata)
# check with 2 element ImageJMetaDataByteCounts, issue #2006 # check with 2 element ImageJMetaDataByteCounts, issue #2006
@ -76,55 +74,61 @@ class TestFileTiffMetadata(PillowTestCase):
img.save(f, tiffinfo=info) img.save(f, tiffinfo=info)
loaded = Image.open(f) loaded = Image.open(f)
self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (8, len(bindata) - 8))
(8, len(bindata) - 8)) self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (8, len(bindata) - 8))
self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts],
(8, len(bindata) - 8))
def test_read_metadata(self): def test_read_metadata(self):
img = Image.open('Tests/images/hopper_g4.tif') img = Image.open("Tests/images/hopper_g4.tif")
self.assertEqual({'YResolution': IFDRational(4294967295, 113653537), self.assertEqual(
'PlanarConfiguration': 1, {
'BitsPerSample': (1,), "YResolution": IFDRational(4294967295, 113653537),
'ImageLength': 128, "PlanarConfiguration": 1,
'Compression': 4, "BitsPerSample": (1,),
'FillOrder': 1, "ImageLength": 128,
'RowsPerStrip': 128, "Compression": 4,
'ResolutionUnit': 3, "FillOrder": 1,
'PhotometricInterpretation': 0, "RowsPerStrip": 128,
'PageNumber': (0, 1), "ResolutionUnit": 3,
'XResolution': IFDRational(4294967295, 113653537), "PhotometricInterpretation": 0,
'ImageWidth': 128, "PageNumber": (0, 1),
'Orientation': 1, "XResolution": IFDRational(4294967295, 113653537),
'StripByteCounts': (1968,), "ImageWidth": 128,
'SamplesPerPixel': 1, "Orientation": 1,
'StripOffsets': (8,) "StripByteCounts": (1968,),
}, img.tag_v2.named()) "SamplesPerPixel": 1,
"StripOffsets": (8,),
},
img.tag_v2.named(),
)
self.assertEqual({'YResolution': ((4294967295, 113653537),), self.assertEqual(
'PlanarConfiguration': (1,), {
'BitsPerSample': (1,), "YResolution": ((4294967295, 113653537),),
'ImageLength': (128,), "PlanarConfiguration": (1,),
'Compression': (4,), "BitsPerSample": (1,),
'FillOrder': (1,), "ImageLength": (128,),
'RowsPerStrip': (128,), "Compression": (4,),
'ResolutionUnit': (3,), "FillOrder": (1,),
'PhotometricInterpretation': (0,), "RowsPerStrip": (128,),
'PageNumber': (0, 1), "ResolutionUnit": (3,),
'XResolution': ((4294967295, 113653537),), "PhotometricInterpretation": (0,),
'ImageWidth': (128,), "PageNumber": (0, 1),
'Orientation': (1,), "XResolution": ((4294967295, 113653537),),
'StripByteCounts': (1968,), "ImageWidth": (128,),
'SamplesPerPixel': (1,), "Orientation": (1,),
'StripOffsets': (8,) "StripByteCounts": (1968,),
}, img.tag.named()) "SamplesPerPixel": (1,),
"StripOffsets": (8,),
},
img.tag.named(),
)
def test_write_metadata(self): def test_write_metadata(self):
""" Test metadata writing through the python code """ """ Test metadata writing through the python code """
img = Image.open('Tests/images/hopper.tif') img = Image.open("Tests/images/hopper.tif")
f = self.tempfile('temp.tiff') f = self.tempfile("temp.tiff")
img.save(f, tiffinfo=img.tag) img.save(f, tiffinfo=img.tag)
loaded = Image.open(f) loaded = Image.open(f)
@ -134,42 +138,44 @@ class TestFileTiffMetadata(PillowTestCase):
for k, v in original.items(): for k, v in original.items():
if isinstance(v, IFDRational): if isinstance(v, IFDRational):
original[k] = IFDRational(*_limit_rational(v, 2**31)) original[k] = IFDRational(*_limit_rational(v, 2 ** 31))
elif isinstance(v, tuple) and isinstance(v[0], IFDRational): elif isinstance(v, tuple) and isinstance(v[0], IFDRational):
original[k] = tuple(IFDRational(*_limit_rational(elt, 2**31)) original[k] = tuple(
for elt in v) IFDRational(*_limit_rational(elt, 2 ** 31)) for elt in v
)
ignored = ['StripByteCounts', 'RowsPerStrip', ignored = ["StripByteCounts", "RowsPerStrip", "PageNumber", "StripOffsets"]
'PageNumber', 'StripOffsets']
for tag, value in reloaded.items(): for tag, value in reloaded.items():
if tag in ignored: if tag in ignored:
continue continue
if (isinstance(original[tag], tuple) if isinstance(original[tag], tuple) and isinstance(
and isinstance(original[tag][0], IFDRational)): original[tag][0], IFDRational
):
# Need to compare element by element in the tuple, # Need to compare element by element in the tuple,
# not comparing tuples of object references # not comparing tuples of object references
self.assert_deep_equal(original[tag], self.assert_deep_equal(
value, original[tag],
"%s didn't roundtrip, %s, %s" % value,
(tag, original[tag], value)) "%s didn't roundtrip, %s, %s" % (tag, original[tag], value),
)
else: else:
self.assertEqual(original[tag], self.assertEqual(
value, original[tag],
"%s didn't roundtrip, %s, %s" % value,
(tag, original[tag], value)) "%s didn't roundtrip, %s, %s" % (tag, original[tag], value),
)
for tag, value in original.items(): for tag, value in original.items():
if tag not in ignored: if tag not in ignored:
self.assertEqual( self.assertEqual(value, reloaded[tag], "%s didn't roundtrip" % tag)
value, reloaded[tag], "%s didn't roundtrip" % tag)
def test_no_duplicate_50741_tag(self): def test_no_duplicate_50741_tag(self):
self.assertEqual(tag_ids['MakerNoteSafety'], 50741) self.assertEqual(tag_ids["MakerNoteSafety"], 50741)
self.assertEqual(tag_ids['BestQualityScale'], 50780) self.assertEqual(tag_ids["BestQualityScale"], 50780)
def test_empty_metadata(self): def test_empty_metadata(self):
f = io.BytesIO(b'II*\x00\x08\x00\x00\x00') f = io.BytesIO(b"II*\x00\x08\x00\x00\x00")
head = f.read(8) head = f.read(8)
info = TiffImagePlugin.ImageFileDirectory(head) info = TiffImagePlugin.ImageFileDirectory(head)
# Should not raise struct.error. # Should not raise struct.error.
@ -177,31 +183,31 @@ class TestFileTiffMetadata(PillowTestCase):
def test_iccprofile(self): def test_iccprofile(self):
# https://github.com/python-pillow/Pillow/issues/1462 # https://github.com/python-pillow/Pillow/issues/1462
im = Image.open('Tests/images/hopper.iccprofile.tif') im = Image.open("Tests/images/hopper.iccprofile.tif")
out = self.tempfile('temp.tiff') out = self.tempfile("temp.tiff")
im.save(out) im.save(out)
reloaded = Image.open(out) reloaded = Image.open(out)
self.assertNotIsInstance(im.info['icc_profile'], tuple) self.assertNotIsInstance(im.info["icc_profile"], tuple)
self.assertEqual(im.info['icc_profile'], reloaded.info['icc_profile']) self.assertEqual(im.info["icc_profile"], reloaded.info["icc_profile"])
def test_iccprofile_binary(self): def test_iccprofile_binary(self):
# https://github.com/python-pillow/Pillow/issues/1526 # https://github.com/python-pillow/Pillow/issues/1526
# We should be able to load this, # We should be able to load this,
# but probably won't be able to save it. # but probably won't be able to save it.
im = Image.open('Tests/images/hopper.iccprofile_binary.tif') im = Image.open("Tests/images/hopper.iccprofile_binary.tif")
self.assertEqual(im.tag_v2.tagtype[34675], 1) self.assertEqual(im.tag_v2.tagtype[34675], 1)
self.assertTrue(im.info['icc_profile']) self.assertTrue(im.info["icc_profile"])
def test_iccprofile_save_png(self): def test_iccprofile_save_png(self):
im = Image.open('Tests/images/hopper.iccprofile.tif') im = Image.open("Tests/images/hopper.iccprofile.tif")
outfile = self.tempfile('temp.png') outfile = self.tempfile("temp.png")
im.save(outfile) im.save(outfile)
def test_iccprofile_binary_save_png(self): def test_iccprofile_binary_save_png(self):
im = Image.open('Tests/images/hopper.iccprofile_binary.tif') im = Image.open("Tests/images/hopper.iccprofile_binary.tif")
outfile = self.tempfile('temp.png') outfile = self.tempfile("temp.png")
im.save(outfile) im.save(outfile)
def test_exif_div_zero(self): def test_exif_div_zero(self):
@ -209,8 +215,8 @@ class TestFileTiffMetadata(PillowTestCase):
info = TiffImagePlugin.ImageFileDirectory_v2() info = TiffImagePlugin.ImageFileDirectory_v2()
info[41988] = TiffImagePlugin.IFDRational(0, 0) info[41988] = TiffImagePlugin.IFDRational(0, 0)
out = self.tempfile('temp.tiff') out = self.tempfile("temp.tiff")
im.save(out, tiffinfo=info, compression='raw') im.save(out, tiffinfo=info, compression="raw")
reloaded = Image.open(out) reloaded = Image.open(out)
self.assertEqual(0, reloaded.tag_v2[41988].numerator) self.assertEqual(0, reloaded.tag_v2[41988].numerator)
@ -218,10 +224,11 @@ class TestFileTiffMetadata(PillowTestCase):
def test_expty_values(self): def test_expty_values(self):
data = io.BytesIO( data = io.BytesIO(
b'II*\x00\x08\x00\x00\x00\x03\x00\x1a\x01\x05\x00\x00\x00\x00\x00' b"II*\x00\x08\x00\x00\x00\x03\x00\x1a\x01\x05\x00\x00\x00\x00\x00"
b'\x00\x00\x00\x00\x1b\x01\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00' b"\x00\x00\x00\x00\x1b\x01\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00"
b'\x98\x82\x02\x00\x07\x00\x00\x002\x00\x00\x00\x00\x00\x00\x00a ' b"\x98\x82\x02\x00\x07\x00\x00\x002\x00\x00\x00\x00\x00\x00\x00a "
b'text\x00\x00') b"text\x00\x00"
)
head = data.read(8) head = data.read(8)
info = TiffImagePlugin.ImageFileDirectory_v2(head) info = TiffImagePlugin.ImageFileDirectory_v2(head)
info.load(data) info.load(data)
@ -230,10 +237,10 @@ class TestFileTiffMetadata(PillowTestCase):
self.assertIn(33432, info) self.assertIn(33432, info)
def test_PhotoshopInfo(self): def test_PhotoshopInfo(self):
im = Image.open('Tests/images/issue_2278.tif') im = Image.open("Tests/images/issue_2278.tif")
self.assertIsInstance(im.tag_v2[34377], bytes) self.assertIsInstance(im.tag_v2[34377], bytes)
out = self.tempfile('temp.tiff') out = self.tempfile("temp.tiff")
im.save(out) im.save(out)
reloaded = Image.open(out) reloaded = Image.open(out)
self.assertIsInstance(reloaded.tag_v2[34377], bytes) self.assertIsInstance(reloaded.tag_v2[34377], bytes)
@ -242,7 +249,7 @@ class TestFileTiffMetadata(PillowTestCase):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
# 277: ("SamplesPerPixel", SHORT, 1), # 277: ("SamplesPerPixel", SHORT, 1),
ifd._tagdata[277] = struct.pack('hh', 4, 4) ifd._tagdata[277] = struct.pack("hh", 4, 4)
ifd.tagtype[277] = TiffTags.SHORT ifd.tagtype[277] = TiffTags.SHORT
# Should not raise ValueError. # Should not raise ValueError.

View File

@ -4,7 +4,6 @@ from PIL import WalImageFile
class TestFileWal(PillowTestCase): class TestFileWal(PillowTestCase):
def test_open(self): def test_open(self):
# Arrange # Arrange
TEST_FILE = "Tests/images/hopper.wal" TEST_FILE = "Tests/images/hopper.wal"

View File

@ -4,6 +4,7 @@ from PIL import Image, WebPImagePlugin
try: try:
from PIL import _webp from PIL import _webp
HAVE_WEBP = True HAVE_WEBP = True
except ImportError: except ImportError:
HAVE_WEBP = False HAVE_WEBP = False
@ -16,8 +17,7 @@ class TestUnsupportedWebp(PillowTestCase):
file_path = "Tests/images/hopper.webp" file_path = "Tests/images/hopper.webp"
self.assert_warning( self.assert_warning(
UserWarning, UserWarning, lambda: self.assertRaises(IOError, Image.open, file_path)
lambda: self.assertRaises(IOError, Image.open, file_path)
) )
if HAVE_WEBP: if HAVE_WEBP:
@ -26,7 +26,6 @@ class TestUnsupportedWebp(PillowTestCase):
@unittest.skipIf(not HAVE_WEBP, "WebP support not installed") @unittest.skipIf(not HAVE_WEBP, "WebP support not installed")
class TestFileWebp(PillowTestCase): class TestFileWebp(PillowTestCase):
def setUp(self): def setUp(self):
self.rgb_mode = "RGB" self.rgb_mode = "RGB"
@ -51,7 +50,8 @@ class TestFileWebp(PillowTestCase):
# generated with: # generated with:
# dwebp -ppm ../../Tests/images/hopper.webp -o hopper_webp_bits.ppm # dwebp -ppm ../../Tests/images/hopper.webp -o hopper_webp_bits.ppm
self.assert_image_similar_tofile( self.assert_image_similar_tofile(
image, 'Tests/images/hopper_webp_bits.ppm', 1.0) image, "Tests/images/hopper_webp_bits.ppm", 1.0
)
def test_write_rgb(self): def test_write_rgb(self):
""" """
@ -72,7 +72,8 @@ class TestFileWebp(PillowTestCase):
# generated with: dwebp -ppm temp.webp -o hopper_webp_write.ppm # generated with: dwebp -ppm temp.webp -o hopper_webp_write.ppm
self.assert_image_similar_tofile( self.assert_image_similar_tofile(
image, 'Tests/images/hopper_webp_write.ppm', 12.0) image, "Tests/images/hopper_webp_write.ppm", 12.0
)
# This test asserts that the images are similar. If the average pixel # This test asserts that the images are similar. If the average pixel
# difference between the two images is less than the epsilon value, # difference between the two images is less than the epsilon value,
@ -149,12 +150,13 @@ class TestFileWebp(PillowTestCase):
def test_file_pointer_could_be_reused(self): def test_file_pointer_could_be_reused(self):
file_path = "Tests/images/hopper.webp" file_path = "Tests/images/hopper.webp"
with open(file_path, 'rb') as blob: with open(file_path, "rb") as blob:
Image.open(blob).load() Image.open(blob).load()
Image.open(blob).load() Image.open(blob).load()
@unittest.skipUnless(HAVE_WEBP and _webp.HAVE_WEBPANIM, @unittest.skipUnless(
"WebP save all not available") HAVE_WEBP and _webp.HAVE_WEBPANIM, "WebP save all not available"
)
def test_background_from_gif(self): def test_background_from_gif(self):
im = Image.open("Tests/images/chi.gif") im = Image.open("Tests/images/chi.gif")
original_value = im.convert("RGB").getpixel((1, 1)) original_value = im.convert("RGB").getpixel((1, 1))
@ -169,6 +171,7 @@ class TestFileWebp(PillowTestCase):
reread = Image.open(out_gif) reread = Image.open(out_gif)
reread_value = reread.convert("RGB").getpixel((1, 1)) reread_value = reread.convert("RGB").getpixel((1, 1))
difference = sum([abs(original_value[i] - reread_value[i]) difference = sum(
for i in range(0, 3)]) [abs(original_value[i] - reread_value[i]) for i in range(0, 3)]
)
self.assertLess(difference, 5) self.assertLess(difference, 5)

View File

@ -10,11 +10,11 @@ except ImportError:
@unittest.skipIf(_webp is None, "WebP support not installed") @unittest.skipIf(_webp is None, "WebP support not installed")
class TestFileWebpAlpha(PillowTestCase): class TestFileWebpAlpha(PillowTestCase):
def setUp(self): def setUp(self):
if _webp.WebPDecoderBuggyAlpha(self): if _webp.WebPDecoderBuggyAlpha(self):
self.skipTest("Buggy early version of WebP installed, " self.skipTest(
"not testing transparency") "Buggy early version of WebP installed, not testing transparency"
)
def test_read_rgba(self): def test_read_rgba(self):
""" """
@ -34,7 +34,7 @@ class TestFileWebpAlpha(PillowTestCase):
image.tobytes() image.tobytes()
target = Image.open('Tests/images/transparent.png') target = Image.open("Tests/images/transparent.png")
self.assert_image_similar(image, target, 20.0) self.assert_image_similar(image, target, 20.0)
def test_write_lossless_rgb(self): def test_write_lossless_rgb(self):
@ -46,7 +46,7 @@ class TestFileWebpAlpha(PillowTestCase):
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
# temp_file = "temp.webp" # temp_file = "temp.webp"
pil_image = hopper('RGBA') pil_image = hopper("RGBA")
mask = Image.new("RGBA", (64, 64), (128, 128, 128, 128)) mask = Image.new("RGBA", (64, 64), (128, 128, 128, 128))
# Add some partially transparent bits: # Add some partially transparent bits:

View File

@ -4,21 +4,23 @@ from PIL import Image
try: try:
from PIL import _webp from PIL import _webp
HAVE_WEBP = True HAVE_WEBP = True
except ImportError: except ImportError:
HAVE_WEBP = False HAVE_WEBP = False
class TestFileWebpAnimation(PillowTestCase): class TestFileWebpAnimation(PillowTestCase):
def setUp(self): def setUp(self):
if not HAVE_WEBP: if not HAVE_WEBP:
self.skipTest('WebP support not installed') self.skipTest("WebP support not installed")
return return
if not _webp.HAVE_WEBPANIM: if not _webp.HAVE_WEBPANIM:
self.skipTest("WebP library does not contain animation support, " self.skipTest(
"not testing animation") "WebP library does not contain animation support, "
"not testing animation"
)
def test_n_frames(self): def test_n_frames(self):
""" """
@ -53,8 +55,8 @@ class TestFileWebpAnimation(PillowTestCase):
orig.load() orig.load()
im.load() im.load()
self.assert_image_similar(im, orig.convert("RGBA"), 25.0) self.assert_image_similar(im, orig.convert("RGBA"), 25.0)
orig.seek(orig.n_frames-1) orig.seek(orig.n_frames - 1)
im.seek(im.n_frames-1) im.seek(im.n_frames - 1)
orig.load() orig.load()
im.load() im.load()
self.assert_image_similar(im, orig.convert("RGBA"), 25.0) self.assert_image_similar(im, orig.convert("RGBA"), 25.0)
@ -78,23 +80,27 @@ class TestFileWebpAnimation(PillowTestCase):
im.load() im.load()
self.assert_image_equal(im, frame2.convert("RGBA")) self.assert_image_equal(im, frame2.convert("RGBA"))
frame1 = Image.open('Tests/images/anim_frame1.webp') frame1 = Image.open("Tests/images/anim_frame1.webp")
frame2 = Image.open('Tests/images/anim_frame2.webp') frame2 = Image.open("Tests/images/anim_frame2.webp")
temp_file1 = self.tempfile("temp.webp") temp_file1 = self.tempfile("temp.webp")
frame1.copy().save(temp_file1, frame1.copy().save(
save_all=True, append_images=[frame2], temp_file1, save_all=True, append_images=[frame2], lossless=True
lossless=True) )
check(temp_file1) check(temp_file1)
# Tests appending using a generator # Tests appending using a generator
def imGenerator(ims): def imGenerator(ims):
for im in ims: for im in ims:
yield im yield im
temp_file2 = self.tempfile("temp_generator.webp") temp_file2 = self.tempfile("temp_generator.webp")
frame1.copy().save(temp_file2, frame1.copy().save(
save_all=True, append_images=imGenerator([frame2]), temp_file2,
lossless=True) save_all=True,
append_images=imGenerator([frame2]),
lossless=True,
)
check(temp_file2) check(temp_file2)
def test_timestamp_and_duration(self): def test_timestamp_and_duration(self):
@ -105,11 +111,14 @@ class TestFileWebpAnimation(PillowTestCase):
durations = [0, 10, 20, 30, 40] durations = [0, 10, 20, 30, 40]
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
frame1 = Image.open('Tests/images/anim_frame1.webp') frame1 = Image.open("Tests/images/anim_frame1.webp")
frame2 = Image.open('Tests/images/anim_frame2.webp') frame2 = Image.open("Tests/images/anim_frame2.webp")
frame1.save(temp_file, save_all=True, frame1.save(
append_images=[frame2, frame1, frame2, frame1], temp_file,
duration=durations) save_all=True,
append_images=[frame2, frame1, frame2, frame1],
duration=durations,
)
im = Image.open(temp_file) im = Image.open(temp_file)
self.assertEqual(im.n_frames, 5) self.assertEqual(im.n_frames, 5)
@ -133,18 +142,21 @@ class TestFileWebpAnimation(PillowTestCase):
dur = 33 dur = 33
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
frame1 = Image.open('Tests/images/anim_frame1.webp') frame1 = Image.open("Tests/images/anim_frame1.webp")
frame2 = Image.open('Tests/images/anim_frame2.webp') frame2 = Image.open("Tests/images/anim_frame2.webp")
frame1.save(temp_file, save_all=True, frame1.save(
append_images=[frame2, frame1, frame2, frame1], temp_file,
duration=dur) save_all=True,
append_images=[frame2, frame1, frame2, frame1],
duration=dur,
)
im = Image.open(temp_file) im = Image.open(temp_file)
self.assertEqual(im.n_frames, 5) self.assertEqual(im.n_frames, 5)
self.assertTrue(im.is_animated) self.assertTrue(im.is_animated)
# Traverse frames in reverse, checking timestamps and durations # Traverse frames in reverse, checking timestamps and durations
ts = dur * (im.n_frames-1) ts = dur * (im.n_frames - 1)
for frame in reversed(range(im.n_frames)): for frame in reversed(range(im.n_frames)):
im.seek(frame) im.seek(frame)
im.load() im.load()

View File

@ -4,20 +4,20 @@ from PIL import Image
try: try:
from PIL import _webp from PIL import _webp
HAVE_WEBP = True HAVE_WEBP = True
except ImportError: except ImportError:
HAVE_WEBP = False HAVE_WEBP = False
class TestFileWebpLossless(PillowTestCase): class TestFileWebpLossless(PillowTestCase):
def setUp(self): def setUp(self):
if not HAVE_WEBP: if not HAVE_WEBP:
self.skipTest('WebP support not installed') self.skipTest("WebP support not installed")
return return
if _webp.WebPDecoderVersion() < 0x0200: if _webp.WebPDecoderVersion() < 0x0200:
self.skipTest('lossless not included') self.skipTest("lossless not included")
self.rgb_mode = "RGB" self.rgb_mode = "RGB"

View File

@ -4,20 +4,20 @@ from PIL import Image
try: try:
from PIL import _webp from PIL import _webp
HAVE_WEBP = True HAVE_WEBP = True
except ImportError: except ImportError:
HAVE_WEBP = False HAVE_WEBP = False
class TestFileWebpMetadata(PillowTestCase): class TestFileWebpMetadata(PillowTestCase):
def setUp(self): def setUp(self):
if not HAVE_WEBP: if not HAVE_WEBP:
self.skipTest('WebP support not installed') self.skipTest("WebP support not installed")
return return
if not _webp.HAVE_WEBPMUX: if not _webp.HAVE_WEBPMUX:
self.skipTest('WebPMux support not installed') self.skipTest("WebPMux support not installed")
def test_read_exif_metadata(self): def test_read_exif_metadata(self):
@ -33,8 +33,8 @@ class TestFileWebpMetadata(PillowTestCase):
# camera make # camera make
self.assertEqual(exif[271], "Canon") self.assertEqual(exif[271], "Canon")
jpeg_image = Image.open('Tests/images/flower.jpg') jpeg_image = Image.open("Tests/images/flower.jpg")
expected_exif = jpeg_image.info['exif'] expected_exif = jpeg_image.info["exif"]
self.assertEqual(exif_data, expected_exif) self.assertEqual(exif_data, expected_exif)
@ -43,7 +43,7 @@ class TestFileWebpMetadata(PillowTestCase):
file_path = "Tests/images/flower.jpg" file_path = "Tests/images/flower.jpg"
image = Image.open(file_path) image = Image.open(file_path)
expected_exif = image.info['exif'] expected_exif = image.info["exif"]
test_buffer = BytesIO() test_buffer = BytesIO()
@ -52,11 +52,10 @@ class TestFileWebpMetadata(PillowTestCase):
test_buffer.seek(0) test_buffer.seek(0)
webp_image = Image.open(test_buffer) webp_image = Image.open(test_buffer)
webp_exif = webp_image.info.get('exif', None) webp_exif = webp_image.info.get("exif", None)
self.assertTrue(webp_exif) self.assertTrue(webp_exif)
if webp_exif: if webp_exif:
self.assertEqual( self.assertEqual(webp_exif, expected_exif, "WebP EXIF didn't match")
webp_exif, expected_exif, "WebP EXIF didn't match")
def test_read_icc_profile(self): def test_read_icc_profile(self):
@ -66,10 +65,10 @@ class TestFileWebpMetadata(PillowTestCase):
self.assertEqual(image.format, "WEBP") self.assertEqual(image.format, "WEBP")
self.assertTrue(image.info.get("icc_profile", None)) self.assertTrue(image.info.get("icc_profile", None))
icc = image.info['icc_profile'] icc = image.info["icc_profile"]
jpeg_image = Image.open('Tests/images/flower2.jpg') jpeg_image = Image.open("Tests/images/flower2.jpg")
expected_icc = jpeg_image.info['icc_profile'] expected_icc = jpeg_image.info["icc_profile"]
self.assertEqual(icc, expected_icc) self.assertEqual(icc, expected_icc)
@ -78,7 +77,7 @@ class TestFileWebpMetadata(PillowTestCase):
file_path = "Tests/images/flower2.jpg" file_path = "Tests/images/flower2.jpg"
image = Image.open(file_path) image = Image.open(file_path)
expected_icc_profile = image.info['icc_profile'] expected_icc_profile = image.info["icc_profile"]
test_buffer = BytesIO() test_buffer = BytesIO()
@ -87,20 +86,20 @@ class TestFileWebpMetadata(PillowTestCase):
test_buffer.seek(0) test_buffer.seek(0)
webp_image = Image.open(test_buffer) webp_image = Image.open(test_buffer)
webp_icc_profile = webp_image.info.get('icc_profile', None) webp_icc_profile = webp_image.info.get("icc_profile", None)
self.assertTrue(webp_icc_profile) self.assertTrue(webp_icc_profile)
if webp_icc_profile: if webp_icc_profile:
self.assertEqual( self.assertEqual(
webp_icc_profile, expected_icc_profile, webp_icc_profile, expected_icc_profile, "Webp ICC didn't match"
"Webp ICC didn't match") )
def test_read_no_exif(self): def test_read_no_exif(self):
from io import BytesIO from io import BytesIO
file_path = "Tests/images/flower.jpg" file_path = "Tests/images/flower.jpg"
image = Image.open(file_path) image = Image.open(file_path)
self.assertIn('exif', image.info) self.assertIn("exif", image.info)
test_buffer = BytesIO() test_buffer = BytesIO()
@ -113,23 +112,28 @@ class TestFileWebpMetadata(PillowTestCase):
def test_write_animated_metadata(self): def test_write_animated_metadata(self):
if not _webp.HAVE_WEBPANIM: if not _webp.HAVE_WEBPANIM:
self.skipTest('WebP animation support not available') self.skipTest("WebP animation support not available")
iccp_data = '<iccp_data>'.encode('utf-8') iccp_data = "<iccp_data>".encode("utf-8")
exif_data = '<exif_data>'.encode('utf-8') exif_data = "<exif_data>".encode("utf-8")
xmp_data = '<xmp_data>'.encode('utf-8') xmp_data = "<xmp_data>".encode("utf-8")
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
frame1 = Image.open('Tests/images/anim_frame1.webp') frame1 = Image.open("Tests/images/anim_frame1.webp")
frame2 = Image.open('Tests/images/anim_frame2.webp') frame2 = Image.open("Tests/images/anim_frame2.webp")
frame1.save(temp_file, save_all=True, frame1.save(
append_images=[frame2, frame1, frame2], temp_file,
icc_profile=iccp_data, exif=exif_data, xmp=xmp_data) save_all=True,
append_images=[frame2, frame1, frame2],
icc_profile=iccp_data,
exif=exif_data,
xmp=xmp_data,
)
image = Image.open(temp_file) image = Image.open(temp_file)
self.assertIn('icc_profile', image.info) self.assertIn("icc_profile", image.info)
self.assertIn('exif', image.info) self.assertIn("exif", image.info)
self.assertIn('xmp', image.info) self.assertIn("xmp", image.info)
self.assertEqual(iccp_data, image.info.get('icc_profile', None)) self.assertEqual(iccp_data, image.info.get("icc_profile", None))
self.assertEqual(exif_data, image.info.get('exif', None)) self.assertEqual(exif_data, image.info.get("exif", None))
self.assertEqual(xmp_data, image.info.get('xmp', None)) self.assertEqual(xmp_data, image.info.get("xmp", None))

View File

@ -5,26 +5,25 @@ from PIL import WmfImagePlugin
class TestFileWmf(PillowTestCase): class TestFileWmf(PillowTestCase):
def test_load_raw(self): def test_load_raw(self):
# Test basic EMF open and rendering # Test basic EMF open and rendering
im = Image.open('Tests/images/drawing.emf') im = Image.open("Tests/images/drawing.emf")
if hasattr(Image.core, "drawwmf"): if hasattr(Image.core, "drawwmf"):
# Currently, support for WMF/EMF is Windows-only # Currently, support for WMF/EMF is Windows-only
im.load() im.load()
# Compare to reference rendering # Compare to reference rendering
imref = Image.open('Tests/images/drawing_emf_ref.png') imref = Image.open("Tests/images/drawing_emf_ref.png")
imref.load() imref.load()
self.assert_image_similar(im, imref, 0) self.assert_image_similar(im, imref, 0)
# Test basic WMF open and rendering # Test basic WMF open and rendering
im = Image.open('Tests/images/drawing.wmf') im = Image.open("Tests/images/drawing.wmf")
if hasattr(Image.core, "drawwmf"): if hasattr(Image.core, "drawwmf"):
# Currently, support for WMF/EMF is Windows-only # Currently, support for WMF/EMF is Windows-only
im.load() im.load()
# Compare to reference rendering # Compare to reference rendering
imref = Image.open('Tests/images/drawing_wmf_ref.png') imref = Image.open("Tests/images/drawing_wmf_ref.png")
imref.load() imref.load()
self.assert_image_similar(im, imref, 2.0) self.assert_image_similar(im, imref, 2.0)
@ -34,6 +33,7 @@ class TestFileWmf(PillowTestCase):
def save(self, im, fp, filename): def save(self, im, fp, filename):
self.methodCalled = True self.methodCalled = True
handler = TestHandler() handler = TestHandler()
WmfImagePlugin.register_handler(handler) WmfImagePlugin.register_handler(handler)
@ -47,16 +47,16 @@ class TestFileWmf(PillowTestCase):
def test_load_dpi_rounding(self): def test_load_dpi_rounding(self):
# Round up # Round up
im = Image.open('Tests/images/drawing.emf') im = Image.open("Tests/images/drawing.emf")
self.assertEqual(im.info["dpi"], 1424) self.assertEqual(im.info["dpi"], 1424)
# Round down # Round down
im = Image.open('Tests/images/drawing_roundDown.emf') im = Image.open("Tests/images/drawing_roundDown.emf")
self.assertEqual(im.info["dpi"], 1426) self.assertEqual(im.info["dpi"], 1426)
def test_save(self): def test_save(self):
im = hopper() im = hopper()
for ext in [".wmf", ".emf"]: for ext in [".wmf", ".emf"]:
tmpfile = self.tempfile("temp"+ext) tmpfile = self.tempfile("temp" + ext)
self.assertRaises(IOError, im.save, tmpfile) self.assertRaises(IOError, im.save, tmpfile)

View File

@ -27,14 +27,13 @@ static char basic_bits[] = {
class TestFileXbm(PillowTestCase): class TestFileXbm(PillowTestCase):
def test_pil151(self): def test_pil151(self):
from io import BytesIO from io import BytesIO
im = Image.open(BytesIO(PIL151)) im = Image.open(BytesIO(PIL151))
im.load() im.load()
self.assertEqual(im.mode, '1') self.assertEqual(im.mode, "1")
self.assertEqual(im.size, (32, 32)) self.assertEqual(im.size, (32, 32))
def test_open(self): def test_open(self):
@ -46,7 +45,7 @@ class TestFileXbm(PillowTestCase):
im = Image.open(filename) im = Image.open(filename)
# Assert # Assert
self.assertEqual(im.mode, '1') self.assertEqual(im.mode, "1")
self.assertEqual(im.size, (128, 128)) self.assertEqual(im.size, (128, 128))
def test_open_filename_with_underscore(self): def test_open_filename_with_underscore(self):
@ -58,5 +57,5 @@ class TestFileXbm(PillowTestCase):
im = Image.open(filename) im = Image.open(filename)
# Assert # Assert
self.assertEqual(im.mode, '1') self.assertEqual(im.mode, "1")
self.assertEqual(im.size, (128, 128)) self.assertEqual(im.size, (128, 128))

View File

@ -6,7 +6,6 @@ TEST_FILE = "Tests/images/hopper.xpm"
class TestFileXpm(PillowTestCase): class TestFileXpm(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
im.load() im.load()
@ -15,13 +14,12 @@ class TestFileXpm(PillowTestCase):
self.assertEqual(im.format, "XPM") self.assertEqual(im.format, "XPM")
# large error due to quantization->44 colors. # large error due to quantization->44 colors.
self.assert_image_similar(im.convert('RGB'), hopper('RGB'), 60) self.assert_image_similar(im.convert("RGB"), hopper("RGB"), 60)
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(SyntaxError, XpmImagePlugin.XpmImageFile, invalid_file)
XpmImagePlugin.XpmImageFile, invalid_file)
def test_load_read(self): def test_load_read(self):
# Arrange # Arrange

View File

@ -6,7 +6,6 @@ TEST_FILE = "Tests/images/hopper.p7"
class TestFileXVThumb(PillowTestCase): class TestFileXVThumb(PillowTestCase):
def test_open(self): def test_open(self):
# Act # Act
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
@ -24,13 +23,13 @@ class TestFileXVThumb(PillowTestCase):
bad_file = "Tests/images/hopper_bad.p7" bad_file = "Tests/images/hopper_bad.p7"
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError, XVThumbImagePlugin.XVThumbImageFile, bad_file)
XVThumbImagePlugin.XVThumbImageFile, bad_file)
def test_invalid_file(self): def test_invalid_file(self):
# Arrange # Arrange
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(
XVThumbImagePlugin.XVThumbImageFile, invalid_file) SyntaxError, XVThumbImagePlugin.XVThumbImageFile, invalid_file
)

View File

@ -6,7 +6,6 @@ filename = "Tests/images/courB08.bdf"
class TestFontBdf(PillowTestCase): class TestFontBdf(PillowTestCase):
def test_sanity(self): def test_sanity(self):
with open(filename, "rb") as test_file: with open(filename, "rb") as test_file: