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):
def test_sanity(self):
with open('Tests/images/test.gpl', 'rb') as fp:
with open("Tests/images/test.gpl", "rb") as 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)
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)
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)
def test_get_palette(self):
# 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)
# Act

View File

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

View File

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

View File

@ -8,11 +8,10 @@ import sys
# sample icon file
TEST_FILE = "Tests/images/pillow.icns"
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version')
enable_jpeg2k = hasattr(Image.core, "jp2klib_version")
class TestFileIcns(PillowTestCase):
def test_sanity(self):
# Loading this icon by default should result in the largest size
# (512x512@2x) being loaded
@ -25,7 +24,7 @@ class TestFileIcns(PillowTestCase):
self.assertEqual(im.size, (1024, 1024))
self.assertEqual(im.format, "ICNS")
@unittest.skipIf(sys.platform != 'darwin', "requires macOS")
@unittest.skipIf(sys.platform != "darwin", "requires macOS")
def test_save(self):
im = Image.open(TEST_FILE)
@ -38,12 +37,12 @@ class TestFileIcns(PillowTestCase):
self.assertEqual(reread.size, (1024, 1024))
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):
im = Image.open(TEST_FILE)
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])
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
# dimensions are as expected
im = Image.open(TEST_FILE)
for w, h, r in im.info['sizes']:
for w, h, r in im.info["sizes"]:
wr = w * r
hr = h * r
im2 = Image.open(TEST_FILE)
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.mode, "RGBA")
self.assertEqual(im2.size, (wr, hr))
# Check that we cannot load an incorrect size
@ -74,14 +73,14 @@ class TestFileIcns(PillowTestCase):
def test_older_icon(self):
# 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).
im = Image.open('Tests/images/pillow2.icns')
for w, h, r in im.info['sizes']:
im = Image.open("Tests/images/pillow2.icns")
for w, h, r in im.info["sizes"]:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow2.icns')
im2 = Image.open("Tests/images/pillow2.icns")
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.mode, "RGBA")
self.assertEqual(im2.size, (wr, hr))
def test_jp2_icon(self):
@ -95,18 +94,18 @@ class TestFileIcns(PillowTestCase):
if not enable_jpeg2k:
return
im = Image.open('Tests/images/pillow3.icns')
for w, h, r in im.info['sizes']:
im = Image.open("Tests/images/pillow3.icns")
for w, h, r in im.info["sizes"]:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow3.icns')
im2 = Image.open("Tests/images/pillow3.icns")
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.mode, "RGBA")
self.assertEqual(im2.size, (wr, hr))
def test_getimage(self):
with open(TEST_FILE, 'rb') as fp:
with open(TEST_FILE, "rb") as fp:
icns_file = IcnsImagePlugin.IcnsFile(fp)
im = icns_file.getimage()
@ -118,6 +117,5 @@ class TestFileIcns(PillowTestCase):
self.assertEqual(im.size, (512, 512))
def test_not_an_icns_file(self):
with io.BytesIO(b'invalid\n') as fp:
self.assertRaises(SyntaxError,
IcnsImagePlugin.IcnsFile, fp)
with io.BytesIO(b"invalid\n") as fp:
self.assertRaises(SyntaxError, IcnsImagePlugin.IcnsFile, fp)

View File

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

View File

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

View File

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

View File

@ -15,7 +15,6 @@ TEST_FILE = "Tests/images/hopper.jpg"
class TestFileJpeg(PillowTestCase):
def setUp(self):
if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:
self.skipTest("jpeg support not available")
@ -29,14 +28,13 @@ class TestFileJpeg(PillowTestCase):
im.bytes = test_bytes # for testing only
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
:param size: tuple
:param mode: optional image mode
"""
return Image.frombytes(mode, size,
os.urandom(size[0]*size[1]*len(mode)))
return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))
def test_sanity(self):
@ -54,10 +52,11 @@ class TestFileJpeg(PillowTestCase):
# Test APP/COM reader (@PIL135)
im = Image.open(TEST_FILE)
self.assertEqual(
im.applist[0],
("APP0", b"JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00"))
self.assertEqual(im.applist[1], (
"COM", b"File written by Adobe Photoshop\xa8 4.0\x00"))
im.applist[0], ("APP0", b"JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00")
)
self.assertEqual(
im.applist[1], ("COM", b"File written by Adobe Photoshop\xa8 4.0\x00")
)
self.assertEqual(len(im.applist), 2)
def test_cmyk(self):
@ -72,8 +71,7 @@ class TestFileJpeg(PillowTestCase):
self.assertGreater(y, 0.8)
self.assertEqual(k, 0.0)
# the opposite corner is black
c, m, y, k = [x / 255.0 for x in im.getpixel((
im.size[0]-1, im.size[1]-1))]
c, m, y, k = [x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))]
self.assertGreater(k, 0.9)
# roundtrip, and check again
im = self.roundtrip(im)
@ -82,8 +80,7 @@ class TestFileJpeg(PillowTestCase):
self.assertGreater(m, 0.8)
self.assertGreater(y, 0.8)
self.assertEqual(k, 0.0)
c, m, y, k = [x / 255.0 for x in im.getpixel((
im.size[0]-1, im.size[1]-1))]
c, m, y, k = [x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))]
self.assertGreater(k, 0.9)
def test_dpi(self):
@ -91,6 +88,7 @@ class TestFileJpeg(PillowTestCase):
im = Image.open(TEST_FILE)
im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))
return im.info.get("dpi")
self.assertEqual(test(72), (72, 72))
self.assertEqual(test(300), (300, 300))
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
# using a 4-byte test code should allow us to detect out of
# 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
im1 = self.roundtrip(hopper(), icc_profile=icc_profile)
self.assertEqual(im1.info.get("icc_profile"), icc_profile or None)
test(0)
test(1)
test(3)
test(4)
test(5)
test(65533-14) # full JPEG marker block
test(65533-14+1) # full block plus one byte
test(65533 - 14) # full JPEG marker block
test(65533 - 14 + 1) # full block plus one byte
test(ImageFile.MAXBLOCK) # full buffer block
test(ImageFile.MAXBLOCK+1) # full buffer block plus one byte
test(ImageFile.MAXBLOCK*4+3) # large block
test(ImageFile.MAXBLOCK + 1) # full buffer block plus one byte
test(ImageFile.MAXBLOCK * 4 + 3) # large block
def test_large_icc_meta(self):
# https://github.com/python-pillow/Pillow/issues/148
# Sometimes the meta data on the icc_profile block is bigger than
# 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")
icc_profile = im.info["icc_profile"]
# Should not raise IOError for image with icc larger than image size.
im.save(f, format='JPEG', progressive=True, quality=95,
icc_profile=icc_profile, optimize=True)
im.save(
f,
format="JPEG",
progressive=True,
quality=95,
icc_profile=icc_profile,
optimize=True,
)
def test_optimize(self):
im1 = self.roundtrip(hopper())
@ -156,9 +161,9 @@ class TestFileJpeg(PillowTestCase):
def test_optimize_large_buffer(self):
# https://github.com/python-pillow/Pillow/issues/148
f = self.tempfile('temp.jpg')
f = self.tempfile("temp.jpg")
# 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)
def test_progressive(self):
@ -173,13 +178,13 @@ class TestFileJpeg(PillowTestCase):
self.assertGreaterEqual(im1.bytes, im3.bytes)
def test_progressive_large_buffer(self):
f = self.tempfile('temp.jpg')
f = self.tempfile("temp.jpg")
# 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)
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))
# this requires more bytes than pixels in the image
im.save(f, format="JPEG", progressive=True, quality=100)
@ -187,30 +192,31 @@ class TestFileJpeg(PillowTestCase):
def test_progressive_cmyk_buffer(self):
# Issue 2272, quality 90 cmyk image is tripping the large buffer bug.
f = BytesIO()
im = self.gen_random_image((256, 256), 'CMYK')
im.save(f, format='JPEG', progressive=True, quality=94)
im = self.gen_random_image((256, 256), "CMYK")
im.save(f, format="JPEG", progressive=True, quality=94)
def test_large_exif(self):
# https://github.com/python-pillow/Pillow/issues/148
f = self.tempfile('temp.jpg')
f = self.tempfile("temp.jpg")
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):
im = Image.open('Tests/images/exif_typeerror.jpg')
im = Image.open("Tests/images/exif_typeerror.jpg")
# Should not raise a TypeError
im._getexif()
def test_exif_gps(self):
# Arrange
im = Image.open('Tests/images/exif_gps.jpg')
im = Image.open("Tests/images/exif_gps.jpg")
gps_index = 34853
expected_exif_gps = {
0: b'\x00\x00\x00\x01',
0: b"\x00\x00\x00\x01",
2: (4294967295, 1),
5: b'\x01',
5: b"\x01",
30: 65535,
29: '1999:99:99 99:99:99'}
29: "1999:99:99 99:99:99",
}
# Act
exif = im._getexif()
@ -222,35 +228,39 @@ class TestFileJpeg(PillowTestCase):
# 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
# this test passes on 2.9 and 3.1, but not 3.0
expected_exif = {34867: 4294967295,
expected_exif = {
34867: 4294967295,
258: (24, 24, 24),
36867: '2099:09:29 10:10:10',
34853: {0: b'\x00\x00\x00\x01',
36867: "2099:09:29 10:10:10",
34853: {
0: b"\x00\x00\x00\x01",
2: (4294967295, 1),
5: b'\x01',
5: b"\x01",
30: 65535,
29: '1999:99:99 99:99:99'},
29: "1999:99:99 99:99:99",
},
296: 65535,
34665: 185,
41994: 65535,
514: 4294967295,
271: 'Make',
272: 'XXX-XXX',
305: 'PIL',
271: "Make",
272: "XXX-XXX",
305: "PIL",
42034: ((1, 1), (1, 1), (1, 1), (1, 1)),
42035: 'LensMake',
34856: b'\xaa\xaa\xaa\xaa\xaa\xaa',
42035: "LensMake",
34856: b"\xaa\xaa\xaa\xaa\xaa\xaa",
282: (4294967295, 1),
33434: (4294967295, 1)}
33434: (4294967295, 1),
}
im = Image.open('Tests/images/exif_gps.jpg')
im = Image.open("Tests/images/exif_gps.jpg")
exif = im._getexif()
for tag, value in expected_exif.items():
self.assertEqual(value, exif[tag])
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
im._getexif()
@ -291,6 +301,7 @@ class TestFileJpeg(PillowTestCase):
def getsampling(im):
layer = im.layer
return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]
# experimental API
im = self.roundtrip(hopper(), subsampling=-1) # default
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")
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
self.assertRaises(
TypeError, self.roundtrip, hopper(), subsampling="1:1:1")
self.assertRaises(TypeError, self.roundtrip, hopper(), subsampling="1:1:1")
def test_exif(self):
im = Image.open("Tests/images/pil_sample_rgb.jpg")
info = im._getexif()
self.assertEqual(info[305], 'Adobe Photoshop CS Macintosh')
self.assertEqual(info[305], "Adobe Photoshop CS Macintosh")
def test_mp(self):
im = Image.open("Tests/images/pil_sample_rgb.jpg")
@ -327,16 +337,16 @@ class TestFileJpeg(PillowTestCase):
def test_quality_keep(self):
# RGB
im = Image.open("Tests/images/hopper.jpg")
f = self.tempfile('temp.jpg')
im.save(f, quality='keep')
f = self.tempfile("temp.jpg")
im.save(f, quality="keep")
# Grayscale
im = Image.open("Tests/images/hopper_gray.jpg")
f = self.tempfile('temp.jpg')
im.save(f, quality='keep')
f = self.tempfile("temp.jpg")
im.save(f, quality="keep")
# CMYK
im = Image.open("Tests/images/pil_sample_cmyk.jpg")
f = self.tempfile('temp.jpg')
im.save(f, quality='keep')
f = self.tempfile("temp.jpg")
im.save(f, quality="keep")
def test_junk_jpeg_header(self):
# https://github.com/python-pillow/Pillow/issues/630
@ -364,8 +374,8 @@ class TestFileJpeg(PillowTestCase):
def _n_qtables_helper(self, n, test_file):
im = Image.open(test_file)
f = self.tempfile('temp.jpg')
im.save(f, qtables=[[n]*64]*n)
f = self.tempfile("temp.jpg")
im.save(f, qtables=[[n] * 64] * n)
im = Image.open(f)
self.assertEqual(len(im.quantization), n)
reloaded = self.roundtrip(im, qtables="keep")
@ -376,18 +386,18 @@ class TestFileJpeg(PillowTestCase):
qtables = im.quantization
reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)
self.assertEqual(im.quantization, reloaded.quantization)
self.assert_image_similar(im, self.roundtrip(im, qtables='web_low'),
30)
self.assert_image_similar(im, self.roundtrip(im, qtables='web_high'),
30)
self.assert_image_similar(im, self.roundtrip(im, qtables='keep'), 30)
self.assert_image_similar(im, self.roundtrip(im, qtables="web_low"), 30)
self.assert_image_similar(im, self.roundtrip(im, qtables="web_high"), 30)
self.assert_image_similar(im, self.roundtrip(im, qtables="keep"), 30)
# valid bounds for baseline qtable
bounds_qtable = [int(s) for s in ("255 1 " * 32).split(None)]
self.roundtrip(im, qtables=[bounds_qtable])
# 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
12 12 14 19 26 58 60 55
14 13 16 24 40 57 69 56
@ -396,9 +406,14 @@ class TestFileJpeg(PillowTestCase):
24 35 55 64 81 104 113 92
49 64 78 87 103 121 120 101
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
18 21 26 66 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
""".split(None)]
""".split(
None
)
]
# list of qtable lists
self.assert_image_similar(
im, self.roundtrip(
im, qtables=[standard_l_qtable, standard_chrominance_qtable]),
30)
im,
self.roundtrip(
im, qtables=[standard_l_qtable, standard_chrominance_qtable]
),
30,
)
# tuple of qtable lists
self.assert_image_similar(
im, self.roundtrip(
im, qtables=(standard_l_qtable, standard_chrominance_qtable)),
30)
im,
self.roundtrip(
im, qtables=(standard_l_qtable, standard_chrominance_qtable)
),
30,
)
# dict of qtable lists
self.assert_image_similar(im,
self.roundtrip(im, qtables={
0: standard_l_qtable,
1: standard_chrominance_qtable
}), 30)
self.assert_image_similar(
im,
self.roundtrip(
im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}
),
30,
)
self._n_qtables_helper(1, "Tests/images/hopper_gray.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")
# not a sequence
self.assertRaises(ValueError, self.roundtrip, im, qtables='a')
self.assertRaises(ValueError, self.roundtrip, im, qtables="a")
# sequence wrong length
self.assertRaises(ValueError, self.roundtrip, im, qtables=[])
# sequence wrong length
self.assertRaises(ValueError,
self.roundtrip, im, qtables=[1, 2, 3, 4, 5])
self.assertRaises(ValueError, self.roundtrip, im, qtables=[1, 2, 3, 4, 5])
# qtable entry not a sequence
self.assertRaises(ValueError, self.roundtrip, im, qtables=[1])
# qtable entry has wrong number of items
self.assertRaises(ValueError,
self.roundtrip, im, qtables=[[1, 2, 3, 4]])
self.assertRaises(ValueError, self.roundtrip, im, qtables=[[1, 2, 3, 4]])
@unittest.skipUnless(djpeg_available(), "djpeg not available")
def test_load_djpeg(self):
@ -468,11 +492,12 @@ class TestFileJpeg(PillowTestCase):
def test_no_duplicate_0x1001_tag(self):
# Arrange
from PIL import ExifTags
tag_ids = {v: k for k, v in ExifTags.TAGS.items()}
# Assert
self.assertEqual(tag_ids['RelatedImageWidth'], 0x1001)
self.assertEqual(tag_ids['RelatedImageLength'], 0x1002)
self.assertEqual(tag_ids["RelatedImageWidth"], 0x1001)
self.assertEqual(tag_ids["RelatedImageLength"], 0x1002)
def test_MAXBLOCK_scaling(self):
im = self.gen_random_image((512, 512))
@ -482,9 +507,9 @@ class TestFileJpeg(PillowTestCase):
reloaded = Image.open(f)
# none of these should crash
reloaded.save(f, quality='keep')
reloaded.save(f, quality='keep', progressive=True)
reloaded.save(f, quality='keep', optimize=True)
reloaded.save(f, quality="keep")
reloaded.save(f, quality="keep", progressive=True)
reloaded.save(f, quality="keep", optimize=True)
def test_bad_mpo_header(self):
""" Treat unknown MPO as JPEG """
@ -500,14 +525,14 @@ class TestFileJpeg(PillowTestCase):
def test_save_correct_modes(self):
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.save(out, "JPEG")
def test_save_wrong_modes(self):
# ref https://github.com/python-pillow/Pillow/issues/2005
out = BytesIO()
for mode in ['LA', 'La', 'RGBA', 'RGBa', 'P']:
for mode in ["LA", "La", "RGBA", "RGBa", "P"]:
img = Image.new(mode, (20, 20))
self.assertRaises(IOError, img.save, out, "JPEG")
@ -517,25 +542,25 @@ class TestFileJpeg(PillowTestCase):
im = Image.open("Tests/images/hopper.tif")
# Act
im.save(outfile, 'JPEG', dpi=im.info['dpi'])
im.save(outfile, "JPEG", dpi=im.info["dpi"])
# Assert
reloaded = Image.open(outfile)
reloaded.load()
self.assertEqual(im.info['dpi'], reloaded.info['dpi'])
self.assertEqual(im.info["dpi"], reloaded.info["dpi"])
def test_load_dpi_rounding(self):
# 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))
# 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))
def test_save_dpi_rounding(self):
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))
reloaded = Image.open(outfile)
@ -609,23 +634,26 @@ class TestFileJpeg(PillowTestCase):
im = Image.open("Tests/images/exif-ifd-offset.jpg")
# 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):
im = Image.open("Tests/images/photoshop-200dpi.jpg")
self.assertEqual(im.info["photoshop"][0x03ed], {
'XResolution': 200.0,
'DisplayedUnitsX': 1,
'YResolution': 200.0,
'DisplayedUnitsY': 1,
})
self.assertEqual(
im.info["photoshop"][0x03ED],
{
"XResolution": 200.0,
"DisplayedUnitsX": 1,
"YResolution": 200.0,
"DisplayedUnitsY": 1,
},
)
# This image does not contain a Photoshop header string
im = Image.open("Tests/images/app13.jpg")
self.assertNotIn("photoshop", im.info)
@unittest.skipUnless(sys.platform.startswith('win32'), "Windows only")
@unittest.skipUnless(sys.platform.startswith("win32"), "Windows only")
class TestFileCloseW32(PillowTestCase):
def setUp(self):
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)
test_card = Image.open('Tests/images/test-card.png')
test_card = Image.open("Tests/images/test-card.png")
test_card.load()
# OpenJPEG 2.0.0 outputs this debugging message sometimes; we should
@ -14,10 +14,9 @@ test_card.load()
class TestFileJpeg2k(PillowTestCase):
def setUp(self):
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):
out = BytesIO()
@ -31,29 +30,28 @@ class TestFileJpeg2k(PillowTestCase):
def test_sanity(self):
# 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()
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.format, 'JPEG2000')
self.assertEqual(im.get_format_mimetype(), 'image/jp2')
self.assertEqual(im.format, "JPEG2000")
self.assertEqual(im.get_format_mimetype(), "image/jp2")
def test_jpf(self):
im = Image.open('Tests/images/balloon.jpf')
self.assertEqual(im.format, 'JPEG2000')
self.assertEqual(im.get_format_mimetype(), 'image/jpx')
im = Image.open("Tests/images/balloon.jpf")
self.assertEqual(im.format, "JPEG2000")
self.assertEqual(im.get_format_mimetype(), "image/jpx")
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
Jpeg2KImagePlugin.Jpeg2KImageFile, invalid_file)
self.assertRaises(SyntaxError, Jpeg2KImagePlugin.Jpeg2KImageFile, invalid_file)
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())
im = Image.open(data)
im.load()
@ -63,14 +61,14 @@ class TestFileJpeg2k(PillowTestCase):
# PIL (they were made using Adobe Photoshop)
def test_lossless(self):
im = Image.open('Tests/images/test-card-lossless.jp2')
im = Image.open("Tests/images/test-card-lossless.jp2")
im.load()
outfile = self.tempfile('temp_test-card.png')
outfile = self.tempfile("temp_test-card.png")
im.save(outfile)
self.assert_image_similar(im, test_card, 1.0e-3)
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()
self.assert_image_similar(im, test_card, 2.0)
@ -88,8 +86,8 @@ class TestFileJpeg2k(PillowTestCase):
def test_tiled_offset_rt(self):
im = self.roundtrip(
test_card, tile_size=(128, 128),
tile_offset=(0, 0), offset=(32, 32))
test_card, tile_size=(128, 128), tile_offset=(0, 0), offset=(32, 32)
)
self.assert_image_equal(im, test_card)
def test_irreversible_rt(self):
@ -97,40 +95,34 @@ class TestFileJpeg2k(PillowTestCase):
self.assert_image_similar(im, test_card, 2.0)
def test_prog_qual_rt(self):
im = self.roundtrip(
test_card, quality_layers=[60, 40, 20], progression='LRCP')
im = self.roundtrip(test_card, quality_layers=[60, 40, 20], progression="LRCP")
self.assert_image_similar(im, test_card, 2.0)
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)
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.load()
self.assertEqual(im.size, (160, 120))
def test_layers_type(self):
outfile = self.tempfile('temp_layers.jp2')
for quality_layers in [
[100, 50, 10],
(100, 50, 10),
None
]:
outfile = self.tempfile("temp_layers.jp2")
for quality_layers in [[100, 50, 10], (100, 50, 10), None]:
test_card.save(outfile, quality_layers=quality_layers)
for quality_layers in [
'quality_layers',
('100', '50', '10')
]:
self.assertRaises(ValueError, test_card.save, outfile,
quality_layers=quality_layers)
for quality_layers in ["quality_layers", ("100", "50", "10")]:
self.assertRaises(
ValueError, test_card.save, outfile, quality_layers=quality_layers
)
def test_layers(self):
out = BytesIO()
test_card.save(out, 'JPEG2000', quality_layers=[100, 50, 10],
progression='LRCP')
test_card.save(
out, "JPEG2000", quality_layers=[100, 50, 10], progression="LRCP"
)
out.seek(0)
im = Image.open(out)
@ -146,49 +138,49 @@ class TestFileJpeg2k(PillowTestCase):
def test_rgba(self):
# Arrange
j2k = Image.open('Tests/images/rgb_trns_ycbc.j2k')
jp2 = Image.open('Tests/images/rgb_trns_ycbc.jp2')
j2k = Image.open("Tests/images/rgb_trns_ycbc.j2k")
jp2 = Image.open("Tests/images/rgb_trns_ycbc.jp2")
# Act
j2k.load()
jp2.load()
# Assert
self.assertEqual(j2k.mode, 'RGBA')
self.assertEqual(jp2.mode, 'RGBA')
self.assertEqual(j2k.mode, "RGBA")
self.assertEqual(jp2.mode, "RGBA")
def test_16bit_monochrome_has_correct_mode(self):
j2k = Image.open('Tests/images/16bit.cropped.j2k')
jp2 = Image.open('Tests/images/16bit.cropped.jp2')
j2k = Image.open("Tests/images/16bit.cropped.j2k")
jp2 = Image.open("Tests/images/16bit.cropped.jp2")
j2k.load()
jp2.load()
self.assertEqual(j2k.mode, 'I;16')
self.assertEqual(jp2.mode, 'I;16')
self.assertEqual(j2k.mode, "I;16")
self.assertEqual(jp2.mode, "I;16")
def test_16bit_monochrome_jp2_like_tiff(self):
tiff_16bit = Image.open('Tests/images/16bit.cropped.tif')
jp2 = Image.open('Tests/images/16bit.cropped.jp2')
tiff_16bit = Image.open("Tests/images/16bit.cropped.tif")
jp2 = Image.open("Tests/images/16bit.cropped.jp2")
self.assert_image_similar(jp2, tiff_16bit, 1e-3)
def test_16bit_monochrome_j2k_like_tiff(self):
tiff_16bit = Image.open('Tests/images/16bit.cropped.tif')
j2k = Image.open('Tests/images/16bit.cropped.j2k')
tiff_16bit = Image.open("Tests/images/16bit.cropped.tif")
j2k = Image.open("Tests/images/16bit.cropped.j2k")
self.assert_image_similar(j2k, tiff_16bit, 1e-3)
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)
self.assert_image_equal(im, j2k)
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)
self.assert_image_equal(im, jp2)
@ -196,12 +188,13 @@ class TestFileJpeg2k(PillowTestCase):
# prepatch, a malformed jp2 file could cause an UnboundLocalError
# exception.
with self.assertRaises(IOError):
Image.open('Tests/images/unbound_variable.jp2')
Image.open("Tests/images/unbound_variable.jp2")
def test_parser_feed(self):
# Arrange
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()
# Act

View File

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

View File

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

View File

@ -4,12 +4,10 @@ from PIL import Image, McIdasImagePlugin
class TestFileMcIdas(PillowTestCase):
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
McIdasImagePlugin.McIdasImageFile, invalid_file)
self.assertRaises(SyntaxError, McIdasImagePlugin.McIdasImageFile, invalid_file)
def test_valid_file(self):
# Arrange

View File

@ -13,9 +13,8 @@ TEST_FILE = "Tests/images/hopper.mic"
@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):
def test_sanity(self):
im = Image.open(TEST_FILE)
im.load()
@ -24,8 +23,8 @@ class TestFileMic(PillowTestCase):
self.assertEqual(im.format, "MIC")
# Adjust for the gamma of 2.2 encoded into the file
lut = ImagePalette.make_gamma_lut(1/2.2)
im = Image.merge('RGBA', [chan.point(lut) for chan in im.split()])
lut = ImagePalette.make_gamma_lut(1 / 2.2)
im = Image.merge("RGBA", [chan.point(lut) for chan in im.split()])
im2 = hopper("RGBA")
self.assert_image_similar(im, im2, 10)
@ -57,10 +56,8 @@ class TestFileMic(PillowTestCase):
def test_invalid_file(self):
# Test an invalid OLE file
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
MicImagePlugin.MicImageFile, invalid_file)
self.assertRaises(SyntaxError, MicImagePlugin.MicImageFile, invalid_file)
# Test a valid OLE file, but not a MIC file
ole_file = "Tests/images/test-ole-file.doc"
self.assertRaises(SyntaxError,
MicImagePlugin.MicImageFile, ole_file)
self.assertRaises(SyntaxError, MicImagePlugin.MicImageFile, ole_file)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,6 +8,7 @@ import sys
try:
from PIL import _webp
HAVE_WEBP = True
except ImportError:
HAVE_WEBP = False
@ -32,7 +33,7 @@ def chunk(cid, *data):
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")
IEND = chunk(b"IEND")
@ -52,7 +53,6 @@ def roundtrip(im, **options):
class TestFilePng(PillowTestCase):
def setUp(self):
if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
self.skipTest("zip/deflate support not available")
@ -86,7 +86,7 @@ class TestFilePng(PillowTestCase):
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
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"]:
im = hopper(mode)
@ -99,8 +99,7 @@ class TestFilePng(PillowTestCase):
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
PngImagePlugin.PngImageFile, invalid_file)
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, invalid_file)
def test_broken(self):
# Check reading of totally broken files. In this case, the test
@ -112,76 +111,83 @@ class TestFilePng(PillowTestCase):
def test_bad_text(self):
# 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, {})
im = load(HEAD + chunk(b'tEXt', b'spam') + TAIL)
self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b"tEXt", b"spam") + TAIL)
self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'tEXt', b'spam\0') + TAIL)
self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b"tEXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'tEXt', b'spam\0egg') + TAIL)
self.assertEqual(im.info, {'spam': 'egg'})
im = load(HEAD + chunk(b"tEXt", b"spam\0egg") + TAIL)
self.assertEqual(im.info, {"spam": "egg"})
im = load(HEAD + chunk(b'tEXt', b'spam\0egg\0') + TAIL)
self.assertEqual(im.info, {'spam': 'egg\x00'})
im = load(HEAD + chunk(b"tEXt", b"spam\0egg\0") + TAIL)
self.assertEqual(im.info, {"spam": "egg\x00"})
def test_bad_ztxt(self):
# 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, {})
im = load(HEAD + chunk(b'zTXt', b'spam') + TAIL)
self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b"zTXt", b"spam") + TAIL)
self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'zTXt', b'spam\0') + TAIL)
self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b"zTXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(b'zTXt', b'spam\0\0') + TAIL)
self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b"zTXt", b"spam\0\0") + TAIL)
self.assertEqual(im.info, {"spam": ""})
im = load(HEAD + chunk(
b'zTXt', b'spam\0\0' + zlib.compress(b'egg')[:1]) + TAIL)
self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")[:1]) + TAIL)
self.assertEqual(im.info, {"spam": ""})
im = load(
HEAD + chunk(b'zTXt', b'spam\0\0' + zlib.compress(b'egg')) + TAIL)
self.assertEqual(im.info, {'spam': 'egg'})
im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")) + TAIL)
self.assertEqual(im.info, {"spam": "egg"})
def test_bad_itxt(self):
im = load(HEAD + chunk(b'iTXt') + TAIL)
im = load(HEAD + chunk(b"iTXt") + TAIL)
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, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0') + TAIL)
im = load(HEAD + chunk(b"iTXt", b"spam\0") + TAIL)
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, {})
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, {})
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"].lang, "en")
self.assertEqual(im.info["spam"].tkey, "Spam")
im = load(HEAD + 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\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' +
zlib.compress(b"egg")) + TAIL)
im = load(
HEAD
+ chunk(b"iTXt", b"spam\0\1\1en\0Spam\0" + zlib.compress(b"egg"))
+ TAIL
)
self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' +
zlib.compress(b"egg")) + TAIL)
im = load(
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"].lang, "en")
self.assertEqual(im.info["spam"].tkey, "Spam")
@ -213,7 +219,7 @@ class TestFilePng(PillowTestCase):
self.assert_image(im, "RGBA", (162, 150))
# 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):
test_file = "Tests/images/rgb_trns.png"
@ -225,7 +231,7 @@ class TestFilePng(PillowTestCase):
self.assert_image(im, "RGBA", (64, 64))
# 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):
in_file = "Tests/images/pil123p.png"
@ -247,7 +253,7 @@ class TestFilePng(PillowTestCase):
self.assert_image(im, "RGBA", (162, 150))
# 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):
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))
# 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):
# check if solid black image with full transparency
@ -292,19 +298,14 @@ class TestFilePng(PillowTestCase):
self.assertEqual(im.getcolors(), [(100, (0, 0, 0, 0))])
def test_save_greyscale_transparency(self):
for mode, num_transparent in {
"1": 1994,
"L": 559,
"I": 559,
}.items():
in_file = "Tests/images/"+mode.lower()+"_trns.png"
for mode, num_transparent in {"1": 1994, "L": 559, "I": 559}.items():
in_file = "Tests/images/" + mode.lower() + "_trns.png"
im = Image.open(in_file)
self.assertEqual(im.mode, mode)
self.assertEqual(im.info["transparency"], 255)
im_rgba = im.convert('RGBA')
self.assertEqual(
im_rgba.getchannel("A").getcolors()[0][0], num_transparent)
im_rgba = im.convert("RGBA")
self.assertEqual(im_rgba.getchannel("A").getcolors()[0][0], num_transparent)
test_file = self.tempfile("temp.png")
im.save(test_file)
@ -314,9 +315,10 @@ class TestFilePng(PillowTestCase):
self.assertEqual(test_im.info["transparency"], 255)
self.assert_image_equal(im, test_im)
test_im_rgba = test_im.convert('RGBA')
test_im_rgba = test_im.convert("RGBA")
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):
in_file = "Tests/images/caption_6_33_22.png"
@ -345,7 +347,7 @@ class TestFilePng(PillowTestCase):
# -14: malformed chunk
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]
im = Image.open(BytesIO(test_file))
@ -355,12 +357,11 @@ class TestFilePng(PillowTestCase):
def test_verify_ignores_crc_error(self):
# check ignores crc errors in ancillary chunks
chunk_data = chunk(b'tEXt', b'spam')
broken_crc_chunk_data = chunk_data[:-1] + b'q' # break CRC
chunk_data = chunk(b"tEXt", b"spam")
broken_crc_chunk_data = chunk_data[:-1] + b"q" # break CRC
image_data = HEAD + broken_crc_chunk_data + TAIL
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile,
BytesIO(image_data))
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data))
ImageFile.LOAD_TRUNCATED_IMAGES = True
try:
@ -372,12 +373,13 @@ class TestFilePng(PillowTestCase):
def test_verify_not_ignores_crc_error_in_required_chunk(self):
# 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
try:
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile,
BytesIO(image_data))
self.assertRaises(
SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data)
)
finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False
@ -417,8 +419,8 @@ class TestFilePng(PillowTestCase):
info.add_text("ZIP", "VALUE", zip=True)
im = roundtrip(im, pnginfo=info)
self.assertEqual(im.info, {'TXT': 'VALUE', 'ZIP': 'VALUE'})
self.assertEqual(im.text, {'TXT': 'VALUE', 'ZIP': 'VALUE'})
self.assertEqual(im.info, {"TXT": "VALUE", "ZIP": "VALUE"})
self.assertEqual(im.text, {"TXT": "VALUE", "ZIP": "VALUE"})
def test_roundtrip_itxt(self):
# Check iTXt roundtripping
@ -426,8 +428,7 @@ class TestFilePng(PillowTestCase):
im = Image.new("RGB", (32, 32))
info = PngImagePlugin.PngInfo()
info.add_itxt("spam", "Eggs", "en", "Spam")
info.add_text("eggs", PngImagePlugin.iTXt("Spam", "en", "Eggs"),
zip=True)
info.add_text("eggs", PngImagePlugin.iTXt("Spam", "en", "Eggs"), zip=True)
im = roundtrip(im, pnginfo=info)
self.assertEqual(im.info, {"spam": "Eggs", "eggs": "Spam"})
@ -459,11 +460,11 @@ class TestFilePng(PillowTestCase):
self.assertEqual(im.info, {"Text": value})
if py3:
rt_text(" Aa" + chr(0xa0) + chr(0xc4) + chr(0xff)) # Latin1
rt_text(chr(0x400) + chr(0x472) + chr(0x4ff)) # Cyrillic
rt_text(chr(0x4e00) + chr(0x66f0) + # CJK
chr(0x9fba) + chr(0x3042) + chr(0xac00))
rt_text("A" + chr(0xc4) + chr(0x472) + chr(0x3042)) # Combined
rt_text(" Aa" + chr(0xA0) + chr(0xC4) + chr(0xFF)) # Latin1
rt_text(chr(0x400) + chr(0x472) + chr(0x4FF)) # Cyrillic
# CJK:
rt_text(chr(0x4E00) + chr(0x66F0) + chr(0x9FBA) + chr(0x3042) + chr(0xAC00))
rt_text("A" + chr(0xC4) + chr(0x472) + chr(0x3042)) # Combined
def test_scary(self):
# 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
# to avoid classification as malware.
with open("Tests/images/pngtest_bad.png.bin", 'rb') as fd:
data = b'\x89' + fd.read()
with open("Tests/images/pngtest_bad.png.bin", "rb") as fd:
data = b"\x89" + fd.read()
pngfile = BytesIO(data)
self.assertRaises(IOError, Image.open, pngfile)
@ -494,17 +495,16 @@ class TestFilePng(PillowTestCase):
def test_trns_p(self):
# Check writing a transparency of 0, issue #528
im = hopper('P')
im.info['transparency'] = 0
im = hopper("P")
im.info["transparency"] = 0
f = self.tempfile("temp.png")
im.save(f)
im2 = Image.open(f)
self.assertIn('transparency', im2.info)
self.assertIn("transparency", im2.info)
self.assert_image_equal(im2.convert('RGBA'),
im.convert('RGBA'))
self.assert_image_equal(im2.convert("RGBA"), im.convert("RGBA"))
def test_trns_null(self):
# Check reading images with null tRNS value, issue #1239
@ -515,39 +515,39 @@ class TestFilePng(PillowTestCase):
def test_save_icc_profile(self):
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")
expected_icc = with_icc.info['icc_profile']
expected_icc = with_icc.info["icc_profile"]
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):
im = Image.open('Tests/images/icc_profile.png')
im = Image.open("Tests/images/icc_profile.png")
im = roundtrip(im, icc_profile=None)
self.assertNotIn('icc_profile', im.info)
self.assertNotIn("icc_profile", im.info)
def test_roundtrip_icc_profile(self):
im = Image.open('Tests/images/icc_profile.png')
expected_icc = im.info['icc_profile']
im = Image.open("Tests/images/icc_profile.png")
expected_icc = im.info["icc_profile"]
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):
im = Image.open("Tests/images/icc_profile_none.png")
self.assertIsNone(im.info['icc_profile'])
self.assertIsNone(im.info["icc_profile"])
im = roundtrip(im)
self.assertNotIn('icc_profile', im.info)
self.assertNotIn("icc_profile", im.info)
def test_repr_png(self):
im = hopper()
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)
def test_chunk_order(self):
@ -579,10 +579,10 @@ class TestFilePng(PillowTestCase):
def test_textual_chunks_after_idat(self):
im = Image.open("Tests/images/hopper.png")
self.assertIn('comment', im.text.keys())
self.assertIn("comment", im.text.keys())
for k, v in {
'date:create': '2014-09-04T09:37:08+03:00',
'date:modify': '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",
}.items():
self.assertEqual(im.text[k], v)
@ -601,7 +601,7 @@ class TestFilePng(PillowTestCase):
# Raises an EOFError in load_end
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):
im = Image.open("Tests/images/exif.png")
@ -637,20 +637,21 @@ class TestFilePng(PillowTestCase):
reloaded = Image.open(test_file)
self.assertEqual(reloaded.info["exif"], b"Exif\x00\x00exifstring")
@unittest.skipUnless(HAVE_WEBP and _webp.HAVE_WEBPANIM,
"WebP support not installed with animation")
@unittest.skipUnless(
HAVE_WEBP and _webp.HAVE_WEBPANIM, "WebP support not installed with animation"
)
def test_apng(self):
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
expected = Image.open("Tests/images/iss634.webp")
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):
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
def setUp(self):
@ -658,7 +659,7 @@ class TestTruncatedPngPLeaks(PillowLeakTestCase):
self.skipTest("zip/deflate support not available")
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))
ImageFile.LOAD_TRUNCATED_IMAGES = True

View File

@ -7,7 +7,6 @@ test_file = "Tests/images/hopper.ppm"
class TestFilePpm(PillowTestCase):
def test_sanity(self):
im = Image.open(test_file)
im.load()
@ -17,39 +16,39 @@ class TestFilePpm(PillowTestCase):
self.assertEqual(im.get_format_mimetype(), "image/x-portable-pixmap")
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()
self.assertEqual(im.mode, 'I')
self.assertEqual(im.mode, "I")
self.assertEqual(im.size, (20, 100))
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)
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()
f = self.tempfile('temp.pgm')
im.save(f, 'PPM')
f = self.tempfile("temp.pgm")
im.save(f, "PPM")
reloaded = Image.open(f)
self.assert_image_equal(im, reloaded)
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)
f = self.tempfile('temp.pnm')
f = self.tempfile("temp.pnm")
im.save(f)
reloaded = Image.open(f)
self.assert_image_equal(im, reloaded)
def test_truncated_file(self):
path = self.tempfile('temp.pgm')
with open(path, 'w') as f:
f.write('P6')
path = self.tempfile("temp.pgm")
with open(path, "w") as f:
f.write("P6")
self.assertRaises(ValueError, Image.open, path)
@ -60,17 +59,17 @@ class TestFilePpm(PillowTestCase):
# sizes.
with self.assertRaises(IOError):
Image.open('Tests/images/negative_size.ppm')
Image.open("Tests/images/negative_size.ppm")
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")
im = Image.open(path)
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")
im = Image.open(path)
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):
def test_sanity(self):
im = Image.open(test_file)
im.load()
@ -20,8 +19,7 @@ class TestImagePsd(PillowTestCase):
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
PsdImagePlugin.PsdImageFile, invalid_file)
self.assertRaises(SyntaxError, PsdImagePlugin.PsdImageFile, invalid_file)
def test_n_frames(self):
im = Image.open("Tests/images/hopper_merged.psd")
@ -35,14 +33,14 @@ class TestImagePsd(PillowTestCase):
def test_eoferror(self):
im = Image.open(test_file)
# 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
self.assertRaises(EOFError, im.seek, n_frames)
self.assertLess(im.tell(), n_frames)
# 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):
im = Image.open(test_file)

View File

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

View File

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

View File

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

View File

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

View File

@ -12,7 +12,6 @@ logger = logging.getLogger(__name__)
class TestFileTiff(PillowTestCase):
def test_sanity(self):
filename = self.tempfile("temp.tif")
@ -44,6 +43,7 @@ class TestFileTiff(PillowTestCase):
def open():
im = Image.open("Tests/images/multipage.tiff")
im.load()
self.assert_warning(None, open)
def test_mac_tiff(self):
@ -54,7 +54,7 @@ class TestFileTiff(PillowTestCase):
self.assertEqual(im.mode, "RGBA")
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()
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.size, (52, 53))
self.assertEqual(im.tile,
[('raw', (0, 0, 52, 53), 160, ('RGBA', 0, 1))])
self.assertEqual(im.tile, [("raw", (0, 0, 52, 53), 160, ("RGBA", 0, 1))])
im.load()
def test_set_legacy_api(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2()
with self.assertRaises(Exception) as e:
ifd.legacy_api = None
self.assertEqual(str(e.exception),
"Not allowing setting of legacy api")
self.assertEqual(str(e.exception), "Not allowing setting of legacy api")
def test_size(self):
filename = "Tests/images/pil168.tif"
@ -81,6 +79,7 @@ class TestFileTiff(PillowTestCase):
def set_size():
im.size = (256, 256)
self.assert_warning(DeprecationWarning, set_size)
def test_xyres_tiff(self):
@ -92,29 +91,24 @@ class TestFileTiff(PillowTestCase):
self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)
# v2 api
self.assertIsInstance(im.tag_v2[X_RESOLUTION],
TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[Y_RESOLUTION],
TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[X_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):
filename = "Tests/images/compression.tif"
im = Image.open(filename)
# v2 api
self.assertIsInstance(im.tag_v2[X_RESOLUTION],
TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[Y_RESOLUTION],
TiffImagePlugin.IFDRational)
self.assertRaises(KeyError,
lambda: im.tag_v2[RESOLUTION_UNIT])
self.assertIsInstance(im.tag_v2[X_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[Y_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertRaises(KeyError, lambda: im.tag_v2[RESOLUTION_UNIT])
# Legacy.
self.assertEqual(im.info['resolution'], (100., 100.))
self.assertEqual(im.info["resolution"], (100.0, 100.0))
# Fallback "inch".
self.assertEqual(im.info['dpi'], (100., 100.))
self.assertEqual(im.info["dpi"], (100.0, 100.0))
def test_int_resolution(self):
filename = "Tests/images/pil168.tif"
@ -124,20 +118,21 @@ class TestFileTiff(PillowTestCase):
im.tag_v2[X_RESOLUTION] = 71
im.tag_v2[Y_RESOLUTION] = 71
im._setup()
self.assertEqual(im.info['dpi'], (71., 71.))
self.assertEqual(im.info["dpi"], (71.0, 71.0))
def test_load_dpi_rounding(self):
for resolutionUnit, dpi in ((None, (72, 73)),
(2, (72, 73)),
(3, (183, 185))):
for resolutionUnit, dpi in ((None, (72, 73)), (2, (72, 73)), (3, (183, 185))):
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.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.info['dpi'], (dpi[1], dpi[1]))
self.assertEqual(im.info["dpi"], (dpi[1], dpi[1]))
def test_save_dpi_rounding(self):
outfile = self.tempfile("temp.tif")
@ -148,12 +143,13 @@ class TestFileTiff(PillowTestCase):
reloaded = Image.open(outfile)
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):
b = BytesIO()
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)
self.assertEqual(float(im.tag_v2[X_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):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
TiffImagePlugin.TiffImageFile, invalid_file)
self.assertRaises(SyntaxError, TiffImagePlugin.TiffImageFile, invalid_file)
TiffImagePlugin.PREFIXES.append(b"\xff\xd8\xff\xe0")
self.assertRaises(SyntaxError,
TiffImagePlugin.TiffImageFile, invalid_file)
self.assertRaises(SyntaxError, TiffImagePlugin.TiffImageFile, invalid_file)
TiffImagePlugin.PREFIXES.pop()
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.
self.assert_warning(UserWarning, i._getexif)
@ -185,38 +179,38 @@ class TestFileTiff(PillowTestCase):
self.assertRaises(IOError, im.save, outfile)
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.mode, 'I;16')
self.assertEqual(im.mode, "I;16")
b = im.tobytes()
# Bytes are in image native order (little endian)
if py3:
self.assertEqual(b[0], ord(b'\xe0'))
self.assertEqual(b[1], ord(b'\x01'))
self.assertEqual(b[0], ord(b"\xe0"))
self.assertEqual(b[1], ord(b"\x01"))
else:
self.assertEqual(b[0], b'\xe0')
self.assertEqual(b[1], b'\x01')
self.assertEqual(b[0], b"\xe0")
self.assertEqual(b[1], b"\x01")
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.mode, 'I;16B')
self.assertEqual(im.mode, "I;16B")
b = im.tobytes()
# Bytes are in image native order (big endian)
if py3:
self.assertEqual(b[0], ord(b'\x01'))
self.assertEqual(b[1], ord(b'\xe0'))
self.assertEqual(b[0], ord(b"\x01"))
self.assertEqual(b[1], ord(b"\xe0"))
else:
self.assertEqual(b[0], b'\x01')
self.assertEqual(b[1], b'\xe0')
self.assertEqual(b[0], b"\x01")
self.assertEqual(b[1], b"\xe0")
def test_16bit_s(self):
im = Image.open('Tests/images/16bit.s.tif')
im = Image.open("Tests/images/16bit.s.tif")
im.load()
self.assertEqual(im.mode, 'I')
self.assertEqual(im.mode, "I")
self.assertEqual(im.getpixel((0, 0)), 32767)
self.assertEqual(im.getpixel((0, 1)), 0)
@ -224,7 +218,7 @@ class TestFileTiff(PillowTestCase):
""" Are we generating the same interpretation
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 --
# 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,
# 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):
# 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.load()
self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)
self.assertEqual(
im.getextrema(), (-3.140936851501465, 3.140684127807617))
self.assertEqual(im.getextrema(), (-3.140936851501465, 3.140684127807617))
def test_unknown_pixel_mode(self):
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):
for path, n_frames in [
['Tests/images/multipage-lastframe.tif', 1],
['Tests/images/multipage.tiff', 3]
["Tests/images/multipage-lastframe.tif", 1],
["Tests/images/multipage.tiff", 3],
]:
im = Image.open(path)
self.assertEqual(im.n_frames, n_frames)
self.assertEqual(im.is_animated, n_frames != 1)
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
# Test seeking past the last frame
@ -266,37 +260,37 @@ class TestFileTiff(PillowTestCase):
self.assertLess(im.tell(), n_frames)
# 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):
# 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
im.seek(0)
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.load()
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.load()
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.load()
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):
im = Image.open('Tests/images/multipage-lastframe.tif')
im = Image.open("Tests/images/multipage-lastframe.tif")
im.load()
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):
filename = "Tests/images/pil136.tiff"
@ -314,16 +308,39 @@ class TestFileTiff(PillowTestCase):
im = Image.open(filename)
# v2 interface
v2_tags = {256: 55, 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}
v2_tags = {
256: 55,
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)
# legacy interface
legacy_tags = {256: (55,), 257: (43,), 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,)}
legacy_tags = {
256: (55,),
257: (43,),
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)
def test__delitem__(self):
@ -351,13 +368,13 @@ class TestFileTiff(PillowTestCase):
ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abcdabcd"
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):
ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abcdefghabcdefgh"
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):
filename = "Tests/images/pil136.tiff"
@ -374,12 +391,14 @@ class TestFileTiff(PillowTestCase):
def test__limit_rational_int(self):
from PIL.TiffImagePlugin import _limit_rational
value = 34
ret = _limit_rational(value, 65536)
self.assertEqual(ret, (34, 1))
def test__limit_rational_float(self):
from PIL.TiffImagePlugin import _limit_rational
value = 22.3
ret = _limit_rational(value, 65536)
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/hopper2R.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif",
)
),
),
(
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/hopper4R.tif",
"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif",
)
),
),
)
original = hopper("L")
@ -426,9 +445,7 @@ class TestFileTiff(PillowTestCase):
self.assert_image_equal(im, im2)
def test_with_underscores(self):
kwargs = {'resolution_unit': 'inch',
'x_resolution': 72,
'y_resolution': 36}
kwargs = {"resolution_unit": "inch", "x_resolution": 72, "y_resolution": 36}
filename = self.tempfile("temp.tif")
hopper("RGB").save(filename, **kwargs)
im = Image.open(filename)
@ -459,8 +476,7 @@ class TestFileTiff(PillowTestCase):
infile = "Tests/images/tiff_strip_raw.tif"
im = Image.open(infile)
self.assert_image_equal_tofile(im,
"Tests/images/tiff_adobe_deflate.png")
self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
def test_strip_planar_raw(self):
# gdal_translate -of GTiff -co INTERLEAVE=BAND \
@ -468,16 +484,14 @@ class TestFileTiff(PillowTestCase):
infile = "Tests/images/tiff_strip_planar_raw.tif"
im = Image.open(infile)
self.assert_image_equal_tofile(im,
"Tests/images/tiff_adobe_deflate.png")
self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
def test_strip_planar_raw_with_overviews(self):
# gdaladdo tiff_strip_planar_raw2.tif 2 4 8 16
infile = "Tests/images/tiff_strip_planar_raw_with_overviews.tif"
im = Image.open(infile)
self.assert_image_equal_tofile(im,
"Tests/images/tiff_adobe_deflate.png")
self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
def test_tiled_planar_raw(self):
# 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"
im = Image.open(infile)
self.assert_image_equal_tofile(im,
"Tests/images/tiff_adobe_deflate.png")
self.assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
def test_palette(self):
for mode in ["P", "PA"]:
@ -513,9 +526,8 @@ class TestFileTiff(PillowTestCase):
# Test appending images
mp = io.BytesIO()
im = Image.new('RGB', (100, 100), '#f00')
ims = [Image.new('RGB', (100, 100), color) for color
in ['#0f0', '#00f']]
im = Image.new("RGB", (100, 100), "#f00")
ims = [Image.new("RGB", (100, 100), color) for color in ["#0f0", "#00f"]]
im.copy().save(mp, format="TIFF", save_all=True, append_images=ims)
mp.seek(0, os.SEEK_SET)
@ -526,9 +538,9 @@ class TestFileTiff(PillowTestCase):
def imGenerator(ims):
for im in ims:
yield im
mp = io.BytesIO()
im.save(mp, format="TIFF", save_all=True,
append_images=imGenerator(ims))
im.save(mp, format="TIFF", save_all=True, append_images=imGenerator(ims))
mp.seek(0, os.SEEK_SET)
reread = Image.open(mp)
@ -539,15 +551,15 @@ class TestFileTiff(PillowTestCase):
# At the time of writing this will only work for non-compressed tiffs
# as libtiff does not support embedded ICC profiles,
# ImageFile._save(..) however does.
im = Image.new('RGB', (1, 1))
im.info['icc_profile'] = 'Dummy value'
im = Image.new("RGB", (1, 1))
im.info["icc_profile"] = "Dummy value"
# Try save-load round trip to make sure both handle icc_profile.
tmpfile = self.tempfile('temp.tif')
im.save(tmpfile, 'TIFF', compression='raw')
tmpfile = self.tempfile("temp.tif")
im.save(tmpfile, "TIFF", compression="raw")
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):
# 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:
im.save(tmpfile)
with open(tmpfile, 'rb') as f:
with open(tmpfile, "rb") as f:
im = Image.open(f)
fp = im.fp
self.assertFalse(fp.closed)
@ -576,7 +588,7 @@ class TestFileTiff(PillowTestCase):
self.assertFalse(fp.closed)
@unittest.skipUnless(sys.platform.startswith('win32'), "Windows only")
@unittest.skipUnless(sys.platform.startswith("win32"), "Windows only")
class TestFileTiffW32(PillowTestCase):
def test_fd_leak(self):
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):
def test_rt_metadata(self):
""" Test writing arbitrary metadata into the tiff image directory
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.
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)
reloaded_textdata = basetextdata + " ?"
floatdata = 12.345
doubledata = 67.89
info = TiffImagePlugin.ImageFileDirectory()
ImageJMetaData = tag_ids['ImageJMetaData']
ImageJMetaDataByteCounts = tag_ids['ImageJMetaDataByteCounts']
ImageDescription = tag_ids['ImageDescription']
ImageJMetaData = tag_ids["ImageJMetaData"]
ImageJMetaDataByteCounts = tag_ids["ImageJMetaDataByteCounts"]
ImageDescription = tag_ids["ImageDescription"]
info[ImageJMetaDataByteCounts] = len(bindata)
info[ImageJMetaData] = bindata
info[tag_ids['RollAngle']] = floatdata
info.tagtype[tag_ids['RollAngle']] = 11
info[tag_ids['YawAngle']] = doubledata
info.tagtype[tag_ids['YawAngle']] = 12
info[tag_ids["RollAngle"]] = floatdata
info.tagtype[tag_ids["RollAngle"]] = 11
info[tag_ids["YawAngle"]] = doubledata
info.tagtype[tag_ids["YawAngle"]] = 12
info[ImageDescription] = textdata
@ -56,8 +55,7 @@ class TestFileTiffMetadata(PillowTestCase):
loaded = Image.open(f)
self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (len(bindata),))
self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts],
(len(bindata),))
self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (len(bindata),))
self.assertEqual(loaded.tag[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_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)
loaded_double = loaded.tag[tag_ids['YawAngle']][0]
loaded_double = loaded.tag[tag_ids["YawAngle"]][0]
self.assertAlmostEqual(loaded_double, doubledata)
# check with 2 element ImageJMetaDataByteCounts, issue #2006
@ -76,55 +74,61 @@ class TestFileTiffMetadata(PillowTestCase):
img.save(f, tiffinfo=info)
loaded = Image.open(f)
self.assertEqual(loaded.tag[ImageJMetaDataByteCounts],
(8, len(bindata) - 8))
self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts],
(8, len(bindata) - 8))
self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (8, len(bindata) - 8))
self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (8, len(bindata) - 8))
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),
'PlanarConfiguration': 1,
'BitsPerSample': (1,),
'ImageLength': 128,
'Compression': 4,
'FillOrder': 1,
'RowsPerStrip': 128,
'ResolutionUnit': 3,
'PhotometricInterpretation': 0,
'PageNumber': (0, 1),
'XResolution': IFDRational(4294967295, 113653537),
'ImageWidth': 128,
'Orientation': 1,
'StripByteCounts': (1968,),
'SamplesPerPixel': 1,
'StripOffsets': (8,)
}, img.tag_v2.named())
self.assertEqual(
{
"YResolution": IFDRational(4294967295, 113653537),
"PlanarConfiguration": 1,
"BitsPerSample": (1,),
"ImageLength": 128,
"Compression": 4,
"FillOrder": 1,
"RowsPerStrip": 128,
"ResolutionUnit": 3,
"PhotometricInterpretation": 0,
"PageNumber": (0, 1),
"XResolution": IFDRational(4294967295, 113653537),
"ImageWidth": 128,
"Orientation": 1,
"StripByteCounts": (1968,),
"SamplesPerPixel": 1,
"StripOffsets": (8,),
},
img.tag_v2.named(),
)
self.assertEqual({'YResolution': ((4294967295, 113653537),),
'PlanarConfiguration': (1,),
'BitsPerSample': (1,),
'ImageLength': (128,),
'Compression': (4,),
'FillOrder': (1,),
'RowsPerStrip': (128,),
'ResolutionUnit': (3,),
'PhotometricInterpretation': (0,),
'PageNumber': (0, 1),
'XResolution': ((4294967295, 113653537),),
'ImageWidth': (128,),
'Orientation': (1,),
'StripByteCounts': (1968,),
'SamplesPerPixel': (1,),
'StripOffsets': (8,)
}, img.tag.named())
self.assertEqual(
{
"YResolution": ((4294967295, 113653537),),
"PlanarConfiguration": (1,),
"BitsPerSample": (1,),
"ImageLength": (128,),
"Compression": (4,),
"FillOrder": (1,),
"RowsPerStrip": (128,),
"ResolutionUnit": (3,),
"PhotometricInterpretation": (0,),
"PageNumber": (0, 1),
"XResolution": ((4294967295, 113653537),),
"ImageWidth": (128,),
"Orientation": (1,),
"StripByteCounts": (1968,),
"SamplesPerPixel": (1,),
"StripOffsets": (8,),
},
img.tag.named(),
)
def test_write_metadata(self):
""" 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)
loaded = Image.open(f)
@ -134,42 +138,44 @@ class TestFileTiffMetadata(PillowTestCase):
for k, v in original.items():
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):
original[k] = tuple(IFDRational(*_limit_rational(elt, 2**31))
for elt in v)
original[k] = tuple(
IFDRational(*_limit_rational(elt, 2 ** 31)) for elt in v
)
ignored = ['StripByteCounts', 'RowsPerStrip',
'PageNumber', 'StripOffsets']
ignored = ["StripByteCounts", "RowsPerStrip", "PageNumber", "StripOffsets"]
for tag, value in reloaded.items():
if tag in ignored:
continue
if (isinstance(original[tag], tuple)
and isinstance(original[tag][0], IFDRational)):
if isinstance(original[tag], tuple) and isinstance(
original[tag][0], IFDRational
):
# Need to compare element by element in the tuple,
# not comparing tuples of object references
self.assert_deep_equal(original[tag],
self.assert_deep_equal(
original[tag],
value,
"%s didn't roundtrip, %s, %s" %
(tag, original[tag], value))
"%s didn't roundtrip, %s, %s" % (tag, original[tag], value),
)
else:
self.assertEqual(original[tag],
self.assertEqual(
original[tag],
value,
"%s didn't roundtrip, %s, %s" %
(tag, original[tag], value))
"%s didn't roundtrip, %s, %s" % (tag, original[tag], value),
)
for tag, value in original.items():
if tag not in ignored:
self.assertEqual(
value, reloaded[tag], "%s didn't roundtrip" % tag)
self.assertEqual(value, reloaded[tag], "%s didn't roundtrip" % tag)
def test_no_duplicate_50741_tag(self):
self.assertEqual(tag_ids['MakerNoteSafety'], 50741)
self.assertEqual(tag_ids['BestQualityScale'], 50780)
self.assertEqual(tag_ids["MakerNoteSafety"], 50741)
self.assertEqual(tag_ids["BestQualityScale"], 50780)
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)
info = TiffImagePlugin.ImageFileDirectory(head)
# Should not raise struct.error.
@ -177,31 +183,31 @@ class TestFileTiffMetadata(PillowTestCase):
def test_iccprofile(self):
# https://github.com/python-pillow/Pillow/issues/1462
im = Image.open('Tests/images/hopper.iccprofile.tif')
out = self.tempfile('temp.tiff')
im = Image.open("Tests/images/hopper.iccprofile.tif")
out = self.tempfile("temp.tiff")
im.save(out)
reloaded = Image.open(out)
self.assertNotIsInstance(im.info['icc_profile'], tuple)
self.assertEqual(im.info['icc_profile'], reloaded.info['icc_profile'])
self.assertNotIsInstance(im.info["icc_profile"], tuple)
self.assertEqual(im.info["icc_profile"], reloaded.info["icc_profile"])
def test_iccprofile_binary(self):
# https://github.com/python-pillow/Pillow/issues/1526
# We should be able to load this,
# 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.assertTrue(im.info['icc_profile'])
self.assertTrue(im.info["icc_profile"])
def test_iccprofile_save_png(self):
im = Image.open('Tests/images/hopper.iccprofile.tif')
outfile = self.tempfile('temp.png')
im = Image.open("Tests/images/hopper.iccprofile.tif")
outfile = self.tempfile("temp.png")
im.save(outfile)
def test_iccprofile_binary_save_png(self):
im = Image.open('Tests/images/hopper.iccprofile_binary.tif')
outfile = self.tempfile('temp.png')
im = Image.open("Tests/images/hopper.iccprofile_binary.tif")
outfile = self.tempfile("temp.png")
im.save(outfile)
def test_exif_div_zero(self):
@ -209,8 +215,8 @@ class TestFileTiffMetadata(PillowTestCase):
info = TiffImagePlugin.ImageFileDirectory_v2()
info[41988] = TiffImagePlugin.IFDRational(0, 0)
out = self.tempfile('temp.tiff')
im.save(out, tiffinfo=info, compression='raw')
out = self.tempfile("temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
reloaded = Image.open(out)
self.assertEqual(0, reloaded.tag_v2[41988].numerator)
@ -218,10 +224,11 @@ class TestFileTiffMetadata(PillowTestCase):
def test_expty_values(self):
data = io.BytesIO(
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'\x98\x82\x02\x00\x07\x00\x00\x002\x00\x00\x00\x00\x00\x00\x00a '
b'text\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"\x98\x82\x02\x00\x07\x00\x00\x002\x00\x00\x00\x00\x00\x00\x00a "
b"text\x00\x00"
)
head = data.read(8)
info = TiffImagePlugin.ImageFileDirectory_v2(head)
info.load(data)
@ -230,10 +237,10 @@ class TestFileTiffMetadata(PillowTestCase):
self.assertIn(33432, info)
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)
out = self.tempfile('temp.tiff')
out = self.tempfile("temp.tiff")
im.save(out)
reloaded = Image.open(out)
self.assertIsInstance(reloaded.tag_v2[34377], bytes)
@ -242,7 +249,7 @@ class TestFileTiffMetadata(PillowTestCase):
ifd = TiffImagePlugin.ImageFileDirectory_v2()
# 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
# Should not raise ValueError.

View File

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

View File

@ -4,6 +4,7 @@ from PIL import Image, WebPImagePlugin
try:
from PIL import _webp
HAVE_WEBP = True
except ImportError:
HAVE_WEBP = False
@ -16,8 +17,7 @@ class TestUnsupportedWebp(PillowTestCase):
file_path = "Tests/images/hopper.webp"
self.assert_warning(
UserWarning,
lambda: self.assertRaises(IOError, Image.open, file_path)
UserWarning, lambda: self.assertRaises(IOError, Image.open, file_path)
)
if HAVE_WEBP:
@ -26,7 +26,6 @@ class TestUnsupportedWebp(PillowTestCase):
@unittest.skipIf(not HAVE_WEBP, "WebP support not installed")
class TestFileWebp(PillowTestCase):
def setUp(self):
self.rgb_mode = "RGB"
@ -51,7 +50,8 @@ class TestFileWebp(PillowTestCase):
# generated with:
# dwebp -ppm ../../Tests/images/hopper.webp -o hopper_webp_bits.ppm
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):
"""
@ -72,7 +72,8 @@ class TestFileWebp(PillowTestCase):
# generated with: dwebp -ppm temp.webp -o hopper_webp_write.ppm
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
# 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):
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()
@unittest.skipUnless(HAVE_WEBP and _webp.HAVE_WEBPANIM,
"WebP save all not available")
@unittest.skipUnless(
HAVE_WEBP and _webp.HAVE_WEBPANIM, "WebP save all not available"
)
def test_background_from_gif(self):
im = Image.open("Tests/images/chi.gif")
original_value = im.convert("RGB").getpixel((1, 1))
@ -169,6 +171,7 @@ class TestFileWebp(PillowTestCase):
reread = Image.open(out_gif)
reread_value = reread.convert("RGB").getpixel((1, 1))
difference = sum([abs(original_value[i] - reread_value[i])
for i in range(0, 3)])
difference = sum(
[abs(original_value[i] - reread_value[i]) for i in range(0, 3)]
)
self.assertLess(difference, 5)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,7 +6,6 @@ TEST_FILE = "Tests/images/hopper.xpm"
class TestFileXpm(PillowTestCase):
def test_sanity(self):
im = Image.open(TEST_FILE)
im.load()
@ -15,13 +14,12 @@ class TestFileXpm(PillowTestCase):
self.assertEqual(im.format, "XPM")
# 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):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
XpmImagePlugin.XpmImageFile, invalid_file)
self.assertRaises(SyntaxError, XpmImagePlugin.XpmImageFile, invalid_file)
def test_load_read(self):
# Arrange

View File

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

View File

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