Convert old tests to use unittest

This commit is contained in:
hugovk 2014-06-10 12:10:47 +03:00
parent c66f332679
commit 3ec505958e
97 changed files with 5162 additions and 4341 deletions

View File

@ -1,24 +1,32 @@
from __future__ import print_function from helper import unittest, PillowTestCase, tearDownModule
from tester import *
import PIL import PIL
import PIL.Image import PIL.Image
# Make sure we have the binary extension
im = PIL.Image.core.new("L", (100, 100))
assert PIL.Image.VERSION[:3] == '1.1' class TestSanity(PillowTestCase):
# Create an image and do stuff with it. def test_sanity(self):
im = PIL.Image.new("1", (100, 100))
assert (im.mode, im.size) == ('1', (100, 100))
assert len(im.tobytes()) == 1300
# Create images in all remaining major modes. # Make sure we have the binary extension
im = PIL.Image.new("L", (100, 100)) im = PIL.Image.core.new("L", (100, 100))
im = PIL.Image.new("P", (100, 100))
im = PIL.Image.new("RGB", (100, 100))
im = PIL.Image.new("I", (100, 100))
im = PIL.Image.new("F", (100, 100))
print("ok") self.assertEqual(PIL.Image.VERSION[:3], '1.1')
# Create an image and do stuff with it.
im = PIL.Image.new("1", (100, 100))
self.assertEqual((im.mode, im.size), ('1', (100, 100)))
self.assertEqual(len(im.tobytes()), 1300)
# Create images in all remaining major modes.
im = PIL.Image.new("L", (100, 100))
im = PIL.Image.new("P", (100, 100))
im = PIL.Image.new("RGB", (100, 100))
im = PIL.Image.new("I", (100, 100))
im = PIL.Image.new("F", (100, 100))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
import os import os
@ -6,81 +6,89 @@ import os
base = os.path.join('Tests', 'images', 'bmp') base = os.path.join('Tests', 'images', 'bmp')
def get_files(d, ext='.bmp'): class TestBmpReference(PillowTestCase):
return [os.path.join(base,d,f) for f
in os.listdir(os.path.join(base, d)) if ext in f]
def test_bad(): def get_files(self, d, ext='.bmp'):
""" These shouldn't crash/dos, but they shouldn't return anything either """ return [os.path.join(base, d, f) for f
for f in get_files('b'): in os.listdir(os.path.join(base, d)) if ext in f]
try:
im = Image.open(f)
im.load()
except Exception as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_questionable(): def test_bad(self):
""" These shouldn't crash/dos, but its not well defined that these are in spec """ """ These shouldn't crash/dos, but they shouldn't return anything
for f in get_files('q'): either """
try: for f in self.get_files('b'):
im = Image.open(f) try:
im.load() im = Image.open(f)
except Exception as msg: im.load()
pass except Exception: # as msg:
# print ("Bad Image %s: %s" %(f,msg)) pass
# print ("Bad Image %s: %s" %(f,msg))
def test_questionable(self):
""" These shouldn't crash/dos, but its not well defined that these
are in spec """
for f in self.get_files('q'):
try:
im = Image.open(f)
im.load()
except Exception: # as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_good(self):
""" These should all work. There's a set of target files in the
html directory that we can compare against. """
# Target files, if they're not just replacing the extension
file_map = {'pal1wb.bmp': 'pal1.png',
'pal4rle.bmp': 'pal4.png',
'pal8-0.bmp': 'pal8.png',
'pal8rle.bmp': 'pal8.png',
'pal8topdown.bmp': 'pal8.png',
'pal8nonsquare.bmp': 'pal8nonsquare-v.png',
'pal8os2.bmp': 'pal8.png',
'pal8os2sp.bmp': 'pal8.png',
'pal8os2v2.bmp': 'pal8.png',
'pal8os2v2-16.bmp': 'pal8.png',
'pal8v4.bmp': 'pal8.png',
'pal8v5.bmp': 'pal8.png',
'rgb16-565pal.bmp': 'rgb16-565.png',
'rgb24pal.bmp': 'rgb24.png',
'rgb32.bmp': 'rgb24.png',
'rgb32bf.bmp': 'rgb24.png'
}
def get_compare(f):
(head, name) = os.path.split(f)
if name in file_map:
return os.path.join(base, 'html', file_map[name])
(name, ext) = os.path.splitext(name)
return os.path.join(base, 'html', "%s.png" % name)
for f in self.get_files('g'):
try:
im = Image.open(f)
im.load()
compare = Image.open(get_compare(f))
compare.load()
if im.mode == 'P':
# assert image similar doesn't really work
# with paletized image, since the palette might
# be differently ordered for an equivalent image.
im = im.convert('RGBA')
compare = im.convert('RGBA')
self.assert_image_similar(im, compare, 5)
except Exception as msg:
# there are three here that are unsupported:
unsupported = (os.path.join(base, 'g', 'rgb32bf.bmp'),
os.path.join(base, 'g', 'pal8rle.bmp'),
os.path.join(base, 'g', 'pal4rle.bmp'))
if f not in unsupported:
self.assertTrue(
False, "Unsupported Image %s: %s" % (f, msg))
def test_good(): if __name__ == '__main__':
""" These should all work. There's a set of target files in the unittest.main()
html directory that we can compare against. """
# Target files, if they're not just replacing the extension
file_map = { 'pal1wb.bmp': 'pal1.png',
'pal4rle.bmp': 'pal4.png',
'pal8-0.bmp': 'pal8.png',
'pal8rle.bmp': 'pal8.png',
'pal8topdown.bmp': 'pal8.png',
'pal8nonsquare.bmp': 'pal8nonsquare-v.png',
'pal8os2.bmp': 'pal8.png',
'pal8os2sp.bmp': 'pal8.png',
'pal8os2v2.bmp': 'pal8.png',
'pal8os2v2-16.bmp': 'pal8.png',
'pal8v4.bmp': 'pal8.png',
'pal8v5.bmp': 'pal8.png',
'rgb16-565pal.bmp': 'rgb16-565.png',
'rgb24pal.bmp': 'rgb24.png',
'rgb32.bmp': 'rgb24.png',
'rgb32bf.bmp': 'rgb24.png'
}
def get_compare(f):
(head, name) = os.path.split(f)
if name in file_map:
return os.path.join(base, 'html', file_map[name])
(name,ext) = os.path.splitext(name)
return os.path.join(base, 'html', "%s.png"%name)
for f in get_files('g'):
try:
im = Image.open(f)
im.load()
compare = Image.open(get_compare(f))
compare.load()
if im.mode == 'P':
# assert image similar doesn't really work
# with paletized image, since the palette might
# be differently ordered for an equivalent image.
im = im.convert('RGBA')
compare = im.convert('RGBA')
assert_image_similar(im, compare,5)
except Exception as msg:
# there are three here that are unsupported:
unsupported = (os.path.join(base, 'g', 'rgb32bf.bmp'),
os.path.join(base, 'g', 'pal8rle.bmp'),
os.path.join(base, 'g', 'pal4rle.bmp'))
if f not in unsupported:
assert_true(False, "Unsupported Image %s: %s" %(f,msg))
# End of file

View File

@ -1,99 +1,136 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
try: try:
import cffi import cffi
from PIL import PyAccess
except: except:
skip() # Skip in setUp()
pass
from PIL import Image, PyAccess
import test_image_putpixel as put from PIL import Image
import test_image_getpixel as get
from test_image_putpixel import TestImagePutPixel
from test_image_getpixel import TestImageGetPixel
Image.USE_CFFI_ACCESS = True Image.USE_CFFI_ACCESS = True
def test_put():
put.test_sanity()
def test_get(): class TestCffiPutPixel(TestImagePutPixel):
get.test_basic()
get.test_signedness()
def _test_get_access(im): def setUp(self):
""" Do we get the same thing as the old pixel access """ try:
import cffi
except:
self.skipTest("No cffi")
""" Using private interfaces, forcing a capi access and a pyaccess for the same image """ def test_put(self):
caccess = im.im.pixel_access(False) self.test_sanity()
access = PyAccess.new(im, False)
w,h = im.size
for x in range(0,w,10):
for y in range(0,h,10):
assert_equal(access[(x,y)], caccess[(x,y)])
def test_get_vs_c():
_test_get_access(lena('RGB'))
_test_get_access(lena('RGBA'))
_test_get_access(lena('L'))
_test_get_access(lena('LA'))
_test_get_access(lena('1'))
_test_get_access(lena('P'))
#_test_get_access(lena('PA')) # PA -- how do I make a PA image???
_test_get_access(lena('F'))
im = Image.new('I;16', (10,10), 40000)
_test_get_access(im)
im = Image.new('I;16L', (10,10), 40000)
_test_get_access(im)
im = Image.new('I;16B', (10,10), 40000)
_test_get_access(im)
im = Image.new('I', (10,10), 40000)
_test_get_access(im)
# These don't actually appear to be modes that I can actually make,
# as unpack sets them directly into the I mode.
#im = Image.new('I;32L', (10,10), -2**10)
#_test_get_access(im)
#im = Image.new('I;32B', (10,10), 2**10)
#_test_get_access(im)
class TestCffiGetPixel(TestImageGetPixel):
def _test_set_access(im, color): def setUp(self):
""" Are we writing the correct bits into the image? """ try:
import cffi
except:
self.skipTest("No cffi")
""" Using private interfaces, forcing a capi access and a pyaccess for the same image """ def test_get(self):
caccess = im.im.pixel_access(False) self.test_basic()
access = PyAccess.new(im, False) self.test_signedness()
w,h = im.size
for x in range(0,w,10):
for y in range(0,h,10):
access[(x,y)] = color
assert_equal(color, caccess[(x,y)])
def test_set_vs_c(): class TestCffi(PillowTestCase):
_test_set_access(lena('RGB'), (255, 128,0) )
_test_set_access(lena('RGBA'), (255, 192, 128, 0))
_test_set_access(lena('L'), 128)
_test_set_access(lena('LA'), (128,128))
_test_set_access(lena('1'), 255)
_test_set_access(lena('P') , 128)
##_test_set_access(i, (128,128)) #PA -- undone how to make
_test_set_access(lena('F'), 1024.0)
im = Image.new('I;16', (10,10), 40000)
_test_set_access(im, 45000)
im = Image.new('I;16L', (10,10), 40000)
_test_set_access(im, 45000)
im = Image.new('I;16B', (10,10), 40000)
_test_set_access(im, 45000)
im = Image.new('I', (10,10), 40000) def setUp(self):
_test_set_access(im, 45000) try:
# im = Image.new('I;32L', (10,10), -(2**10)) import cffi
# _test_set_access(im, -(2**13)+1) except:
#im = Image.new('I;32B', (10,10), 2**10) self.skipTest("No cffi")
#_test_set_access(im, 2**13-1)
def _test_get_access(self, im):
""" Do we get the same thing as the old pixel access """
""" Using private interfaces, forcing a capi access and
a pyaccess for the same image """
caccess = im.im.pixel_access(False)
access = PyAccess.new(im, False)
w, h = im.size
for x in range(0, w, 10):
for y in range(0, h, 10):
self.assertEqual(access[(x, y)], caccess[(x, y)])
def test_get_vs_c(self):
rgb = lena('RGB')
rgb.load()
self._test_get_access(rgb)
self._test_get_access(lena('RGBA'))
self._test_get_access(lena('L'))
self._test_get_access(lena('LA'))
self._test_get_access(lena('1'))
self._test_get_access(lena('P'))
# self._test_get_access(lena('PA')) # PA -- how do I make a PA image?
self._test_get_access(lena('F'))
im = Image.new('I;16', (10, 10), 40000)
self._test_get_access(im)
im = Image.new('I;16L', (10, 10), 40000)
self._test_get_access(im)
im = Image.new('I;16B', (10, 10), 40000)
self._test_get_access(im)
im = Image.new('I', (10, 10), 40000)
self._test_get_access(im)
# These don't actually appear to be modes that I can actually make,
# as unpack sets them directly into the I mode.
# im = Image.new('I;32L', (10, 10), -2**10)
# self._test_get_access(im)
# im = Image.new('I;32B', (10, 10), 2**10)
# self._test_get_access(im)
def _test_set_access(self, im, color):
""" Are we writing the correct bits into the image? """
""" Using private interfaces, forcing a capi access and
a pyaccess for the same image """
caccess = im.im.pixel_access(False)
access = PyAccess.new(im, False)
w, h = im.size
for x in range(0, w, 10):
for y in range(0, h, 10):
access[(x, y)] = color
self.assertEqual(color, caccess[(x, y)])
def test_set_vs_c(self):
rgb = lena('RGB')
rgb.load()
self._test_set_access(rgb, (255, 128, 0))
self._test_set_access(lena('RGBA'), (255, 192, 128, 0))
self._test_set_access(lena('L'), 128)
self._test_set_access(lena('LA'), (128, 128))
self._test_set_access(lena('1'), 255)
self._test_set_access(lena('P'), 128)
# self._test_set_access(i, (128, 128)) #PA -- undone how to make
self._test_set_access(lena('F'), 1024.0)
im = Image.new('I;16', (10, 10), 40000)
self._test_set_access(im, 45000)
im = Image.new('I;16L', (10, 10), 40000)
self._test_set_access(im, 45000)
im = Image.new('I;16B', (10, 10), 40000)
self._test_set_access(im, 45000)
im = Image.new('I', (10, 10), 40000)
self._test_set_access(im, 45000)
# im = Image.new('I;32L', (10, 10), -(2**10))
# self._test_set_access(im, -(2**13)+1)
# im = Image.new('I;32B', (10, 10), 2**10)
# self._test_set_access(im, 2**13-1)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,38 +1,44 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
import io import io
def roundtrip(im):
outfile = tempfile("temp.bmp")
im.save(outfile, 'BMP') class TestFileBmp(PillowTestCase):
reloaded = Image.open(outfile) def roundtrip(self, im):
reloaded.load() outfile = self.tempfile("temp.bmp")
assert_equal(im.mode, reloaded.mode)
assert_equal(im.size, reloaded.size) im.save(outfile, 'BMP')
assert_equal(reloaded.format, "BMP")
reloaded = Image.open(outfile)
reloaded.load()
self.assertEqual(im.mode, reloaded.mode)
self.assertEqual(im.size, reloaded.size)
self.assertEqual(reloaded.format, "BMP")
def test_sanity(self):
self.roundtrip(lena())
self.roundtrip(lena("1"))
self.roundtrip(lena("L"))
self.roundtrip(lena("P"))
self.roundtrip(lena("RGB"))
def test_save_to_bytes(self):
output = io.BytesIO()
im = lena()
im.save(output, "BMP")
output.seek(0)
reloaded = Image.open(output)
self.assertEqual(im.mode, reloaded.mode)
self.assertEqual(im.size, reloaded.size)
self.assertEqual(reloaded.format, "BMP")
def test_sanity(): if __name__ == '__main__':
roundtrip(lena()) unittest.main()
roundtrip(lena("1"))
roundtrip(lena("L"))
roundtrip(lena("P"))
roundtrip(lena("RGB"))
# End of file
def test_save_to_bytes():
output = io.BytesIO()
im = lena()
im.save(output, "BMP")
output.seek(0)
reloaded = Image.open(output)
assert_equal(im.mode, reloaded.mode)
assert_equal(im.size, reloaded.size)
assert_equal(reloaded.format, "BMP")

View File

@ -1,11 +1,8 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image, EpsImagePlugin from PIL import Image, EpsImagePlugin
import io import io
if not EpsImagePlugin.has_ghostscript():
skip()
# Our two EPS test files (they are identical except for their bounding boxes) # Our two EPS test files (they are identical except for their bounding boxes)
file1 = "Tests/images/zero_bb.eps" file1 = "Tests/images/zero_bb.eps"
file2 = "Tests/images/non_zero_bb.eps" file2 = "Tests/images/non_zero_bb.eps"
@ -20,123 +17,127 @@ file2_compare_scale2 = "Tests/images/non_zero_bb_scale2.png"
# EPS test files with binary preview # EPS test files with binary preview
file3 = "Tests/images/binary_preview_map.eps" file3 = "Tests/images/binary_preview_map.eps"
def test_sanity():
# Regular scale
image1 = Image.open(file1)
image1.load()
assert_equal(image1.mode, "RGB")
assert_equal(image1.size, (460, 352))
assert_equal(image1.format, "EPS")
image2 = Image.open(file2) class TestFileEps(PillowTestCase):
image2.load()
assert_equal(image2.mode, "RGB")
assert_equal(image2.size, (360, 252))
assert_equal(image2.format, "EPS")
# Double scale def setUp(self):
image1_scale2 = Image.open(file1) if not EpsImagePlugin.has_ghostscript():
image1_scale2.load(scale=2) self.skipTest("Ghostscript not available")
assert_equal(image1_scale2.mode, "RGB")
assert_equal(image1_scale2.size, (920, 704))
assert_equal(image1_scale2.format, "EPS")
image2_scale2 = Image.open(file2) def test_sanity(self):
image2_scale2.load(scale=2) # Regular scale
assert_equal(image2_scale2.mode, "RGB") image1 = Image.open(file1)
assert_equal(image2_scale2.size, (720, 504)) image1.load()
assert_equal(image2_scale2.format, "EPS") self.assertEqual(image1.mode, "RGB")
self.assertEqual(image1.size, (460, 352))
self.assertEqual(image1.format, "EPS")
image2 = Image.open(file2)
image2.load()
self.assertEqual(image2.mode, "RGB")
self.assertEqual(image2.size, (360, 252))
self.assertEqual(image2.format, "EPS")
def test_file_object(): # Double scale
# issue 479 image1_scale2 = Image.open(file1)
image1 = Image.open(file1) image1_scale2.load(scale=2)
with open(tempfile('temp_file.eps'), 'wb') as fh: self.assertEqual(image1_scale2.mode, "RGB")
image1.save(fh, 'EPS') self.assertEqual(image1_scale2.size, (920, 704))
self.assertEqual(image1_scale2.format, "EPS")
image2_scale2 = Image.open(file2)
image2_scale2.load(scale=2)
self.assertEqual(image2_scale2.mode, "RGB")
self.assertEqual(image2_scale2.size, (720, 504))
self.assertEqual(image2_scale2.format, "EPS")
def test_iobase_object(): def test_file_object(self):
# issue 479 # issue 479
image1 = Image.open(file1) image1 = Image.open(file1)
with io.open(tempfile('temp_iobase.eps'), 'wb') as fh: with open(self.tempfile('temp_file.eps'), 'wb') as fh:
image1.save(fh, 'EPS') image1.save(fh, 'EPS')
def test_iobase_object(self):
# issue 479
image1 = Image.open(file1)
with io.open(self.tempfile('temp_iobase.eps'), 'wb') as fh:
image1.save(fh, 'EPS')
def test_render_scale1(): def test_render_scale1(self):
# We need png support for these render test # We need png support for these render test
codecs = dir(Image.core) codecs = dir(Image.core)
if "zip_encoder" not in codecs or "zip_decoder" not in codecs: if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
skip("zip/deflate support not available") self.skipTest("zip/deflate support not available")
# Zero bounding box # Zero bounding box
image1_scale1 = Image.open(file1) image1_scale1 = Image.open(file1)
image1_scale1.load() image1_scale1.load()
image1_scale1_compare = Image.open(file1_compare).convert("RGB") image1_scale1_compare = Image.open(file1_compare).convert("RGB")
image1_scale1_compare.load() image1_scale1_compare.load()
assert_image_similar(image1_scale1, image1_scale1_compare, 5) self.assert_image_similar(image1_scale1, image1_scale1_compare, 5)
# Non-Zero bounding box # Non-Zero bounding box
image2_scale1 = Image.open(file2) image2_scale1 = Image.open(file2)
image2_scale1.load() image2_scale1.load()
image2_scale1_compare = Image.open(file2_compare).convert("RGB") image2_scale1_compare = Image.open(file2_compare).convert("RGB")
image2_scale1_compare.load() image2_scale1_compare.load()
assert_image_similar(image2_scale1, image2_scale1_compare, 10) self.assert_image_similar(image2_scale1, image2_scale1_compare, 10)
def test_render_scale2(self):
# We need png support for these render test
codecs = dir(Image.core)
if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
self.skipTest("zip/deflate support not available")
def test_render_scale2(): # Zero bounding box
# We need png support for these render test image1_scale2 = Image.open(file1)
codecs = dir(Image.core) image1_scale2.load(scale=2)
if "zip_encoder" not in codecs or "zip_decoder" not in codecs: image1_scale2_compare = Image.open(file1_compare_scale2).convert("RGB")
skip("zip/deflate support not available") image1_scale2_compare.load()
self.assert_image_similar(image1_scale2, image1_scale2_compare, 5)
# Zero bounding box # Non-Zero bounding box
image1_scale2 = Image.open(file1) image2_scale2 = Image.open(file2)
image1_scale2.load(scale=2) image2_scale2.load(scale=2)
image1_scale2_compare = Image.open(file1_compare_scale2).convert("RGB") image2_scale2_compare = Image.open(file2_compare_scale2).convert("RGB")
image1_scale2_compare.load() image2_scale2_compare.load()
assert_image_similar(image1_scale2, image1_scale2_compare, 5) self.assert_image_similar(image2_scale2, image2_scale2_compare, 10)
# Non-Zero bounding box def test_resize(self):
image2_scale2 = Image.open(file2) # Arrange
image2_scale2.load(scale=2) image1 = Image.open(file1)
image2_scale2_compare = Image.open(file2_compare_scale2).convert("RGB") image2 = Image.open(file2)
image2_scale2_compare.load() new_size = (100, 100)
assert_image_similar(image2_scale2, image2_scale2_compare, 10)
# Act
image1 = image1.resize(new_size)
image2 = image2.resize(new_size)
def test_resize(): # Assert
# Arrange self.assertEqual(image1.size, new_size)
image1 = Image.open(file1) self.assertEqual(image2.size, new_size)
image2 = Image.open(file2)
new_size = (100, 100)
# Act def test_thumbnail(self):
image1 = image1.resize(new_size) # Issue #619
image2 = image2.resize(new_size) # Arrange
image1 = Image.open(file1)
image2 = Image.open(file2)
new_size = (100, 100)
# Assert # Act
assert_equal(image1.size, new_size) image1.thumbnail(new_size)
assert_equal(image2.size, new_size) image2.thumbnail(new_size)
# Assert
self.assertEqual(max(image1.size), max(new_size))
self.assertEqual(max(image2.size), max(new_size))
def test_thumbnail(): def test_read_binary_preview(self):
# Issue #619 # Issue 302
# Arrange # open image with binary preview
image1 = Image.open(file1) Image.open(file3)
image2 = Image.open(file2)
new_size = (100, 100)
# Act if __name__ == '__main__':
image1.thumbnail(new_size) unittest.main()
image2.thumbnail(new_size)
# Assert
assert_equal(max(image1.size), max(new_size))
assert_equal(max(image2.size), max(new_size))
def test_read_binary_preview():
# Issue 302
# open image with binary preview
image1 = Image.open(file3)
# End of file # End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
@ -6,9 +6,18 @@ from PIL import Image
file = "Images/lena.fli" file = "Images/lena.fli"
data = open(file, "rb").read() data = open(file, "rb").read()
def test_sanity():
im = Image.open(file) class TestFileFli(PillowTestCase):
im.load()
assert_equal(im.mode, "P") def test_sanity(self):
assert_equal(im.size, (128, 128)) im = Image.open(file)
assert_equal(im.format, "FLI") im.load()
self.assertEqual(im.mode, "P")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "FLI")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,87 +1,96 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
codecs = dir(Image.core) codecs = dir(Image.core)
if "gif_encoder" not in codecs or "gif_decoder" not in codecs:
skip("gif support not available") # can this happen?
# sample gif stream # sample gif stream
file = "Images/lena.gif" file = "Images/lena.gif"
with open(file, "rb") as f: with open(file, "rb") as f:
data = f.read() data = f.read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "P")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "GIF")
def test_optimize(): class TestFileGif(PillowTestCase):
def test(optimize):
im = Image.new("L", (1, 1), 0)
file = BytesIO()
im.save(file, "GIF", optimize=optimize)
return len(file.getvalue())
assert_equal(test(0), 800)
assert_equal(test(1), 38)
def test_roundtrip(): def setUp(self):
out = tempfile('temp.gif') if "gif_encoder" not in codecs or "gif_decoder" not in codecs:
im = lena() self.skipTest("gif support not available") # can this happen?
im.save(out)
reread = Image.open(out)
assert_image_similar(reread.convert('RGB'), im, 50) def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "P")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "GIF")
def test_roundtrip2(): def test_optimize(self):
#see https://github.com/python-pillow/Pillow/issues/403 from io import BytesIO
out = tempfile('temp.gif')
im = Image.open('Images/lena.gif')
im2 = im.copy()
im2.save(out)
reread = Image.open(out)
assert_image_similar(reread.convert('RGB'), lena(), 50) def test(optimize):
im = Image.new("L", (1, 1), 0)
file = BytesIO()
im.save(file, "GIF", optimize=optimize)
return len(file.getvalue())
self.assertEqual(test(0), 800)
self.assertEqual(test(1), 38)
def test_roundtrip(self):
out = self.tempfile('temp.gif')
im = lena()
im.save(out)
reread = Image.open(out)
self.assert_image_similar(reread.convert('RGB'), im, 50)
def test_roundtrip2(self):
# see https://github.com/python-pillow/Pillow/issues/403
out = self.tempfile('temp.gif')
im = Image.open('Images/lena.gif')
im2 = im.copy()
im2.save(out)
reread = Image.open(out)
self.assert_image_similar(reread.convert('RGB'), lena(), 50)
def test_palette_handling(self):
# see https://github.com/python-pillow/Pillow/issues/513
im = Image.open('Images/lena.gif')
im = im.convert('RGB')
im = im.resize((100, 100), Image.ANTIALIAS)
im2 = im.convert('P', palette=Image.ADAPTIVE, colors=256)
f = self.tempfile('temp.gif')
im2.save(f, optimize=True)
reloaded = Image.open(f)
self.assert_image_similar(im, reloaded.convert('RGB'), 10)
def test_palette_434(self):
# see https://github.com/python-pillow/Pillow/issues/434
def roundtrip(im, *args, **kwargs):
out = self.tempfile('temp.gif')
im.save(out, *args, **kwargs)
reloaded = Image.open(out)
return [im, reloaded]
orig = "Tests/images/test.colors.gif"
im = Image.open(orig)
self.assert_image_equal(*roundtrip(im))
self.assert_image_equal(*roundtrip(im, optimize=True))
im = im.convert("RGB")
# check automatic P conversion
reloaded = roundtrip(im)[1].convert('RGB')
self.assert_image_equal(im, reloaded)
def test_palette_handling(): if __name__ == '__main__':
# see https://github.com/python-pillow/Pillow/issues/513 unittest.main()
im = Image.open('Images/lena.gif')
im = im.convert('RGB')
im = im.resize((100,100), Image.ANTIALIAS)
im2 = im.convert('P', palette=Image.ADAPTIVE, colors=256)
f = tempfile('temp.gif')
im2.save(f, optimize=True)
reloaded = Image.open(f)
assert_image_similar(im, reloaded.convert('RGB'), 10)
def test_palette_434():
# see https://github.com/python-pillow/Pillow/issues/434
def roundtrip(im, *args, **kwargs):
out = tempfile('temp.gif')
im.save(out, *args, **kwargs)
reloaded = Image.open(out)
return [im, reloaded]
orig = "Tests/images/test.colors.gif"
im = Image.open(orig)
assert_image_equal(*roundtrip(im))
assert_image_equal(*roundtrip(im, optimize=True))
im = im.convert("RGB")
# check automatic P conversion
reloaded = roundtrip(im)[1].convert('RGB')
assert_image_equal(im, reloaded)
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
@ -8,59 +8,67 @@ data = open(file, "rb").read()
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version') enable_jpeg2k = hasattr(Image.core, 'jp2klib_version')
def test_sanity():
# Loading this icon by default should result in the largest size
# (512x512@2x) being loaded
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGBA")
assert_equal(im.size, (1024, 1024))
assert_equal(im.format, "ICNS")
def test_sizes(): class TestFileIcns(PillowTestCase):
# Check that we can load all of the sizes, and that the final pixel
# dimensions are as expected
im = Image.open(file)
for w,h,r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open(file)
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))
def test_older_icon(): def test_sanity(self):
# This icon was made with Icon Composer rather than iconutil; it still # Loading this icon by default should result in the largest size
# uses PNG rather than JP2, however (since it was made on 10.9). # (512x512@2x) being loaded
im = Image.open('Tests/images/pillow2.icns') im = Image.open(file)
for w,h,r in im.info['sizes']: im.load()
wr = w * r self.assertEqual(im.mode, "RGBA")
hr = h * r self.assertEqual(im.size, (1024, 1024))
im2 = Image.open('Tests/images/pillow2.icns') self.assertEqual(im.format, "ICNS")
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))
def test_jp2_icon(): def test_sizes(self):
# This icon was made by using Uli Kusterer's oldiconutil to replace # Check that we can load all of the sizes, and that the final pixel
# the PNG images with JPEG 2000 ones. The advantage of doing this is # dimensions are as expected
# that OS X 10.5 supports JPEG 2000 but not PNG; some commercial im = Image.open(file)
# software therefore does just this. for w, h, r in im.info['sizes']:
wr = w * r
# (oldiconutil is here: https://github.com/uliwitness/oldiconutil) hr = h * r
im2 = Image.open(file)
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
if not enable_jpeg2k: def test_older_icon(self):
return # 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/pillow3.icns') im = Image.open('Tests/images/pillow2.icns')
for w,h,r in im.info['sizes']: for w, h, r in im.info['sizes']:
wr = w * r wr = w * r
hr = h * r hr = h * r
im2 = Image.open('Tests/images/pillow3.icns') im2 = Image.open('Tests/images/pillow2.icns')
im2.size = (w, h, r) im2.size = (w, h, r)
im2.load() im2.load()
assert_equal(im2.mode, 'RGBA') self.assertEqual(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr)) self.assertEqual(im2.size, (wr, hr))
def test_jp2_icon(self):
# This icon was made by using Uli Kusterer's oldiconutil to replace
# the PNG images with JPEG 2000 ones. The advantage of doing this is
# that OS X 10.5 supports JPEG 2000 but not PNG; some commercial
# software therefore does just this.
# (oldiconutil is here: https://github.com/uliwitness/oldiconutil)
if not enable_jpeg2k:
return
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.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
@ -6,9 +6,18 @@ from PIL import Image
file = "Images/lena.ico" file = "Images/lena.ico"
data = open(file, "rb").read() data = open(file, "rb").read()
def test_sanity():
im = Image.open(file) class TestFileIco(PillowTestCase):
im.load()
assert_equal(im.mode, "RGBA") def test_sanity(self):
assert_equal(im.size, (16, 16)) im = Image.open(file)
assert_equal(im.format, "ICO") im.load()
self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (16, 16))
self.assertEqual(im.format, "ICO")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,238 +1,231 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena, py3
import random import random
from io import BytesIO
from PIL import Image from PIL import Image
from PIL import ImageFile from PIL import ImageFile
codecs = dir(Image.core) codecs = dir(Image.core)
if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:
skip("jpeg support not available")
test_file = "Images/lena.jpg" test_file = "Images/lena.jpg"
def roundtrip(im, **options): class TestFileJpeg(PillowTestCase):
out = BytesIO()
im.save(out, "JPEG", **options)
bytes = out.tell()
out.seek(0)
im = Image.open(out)
im.bytes = bytes # for testing only
return im
# -------------------------------------------------------------------- def setUp(self):
if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:
self.skipTest("jpeg support not available")
def roundtrip(self, im, **options):
out = BytesIO()
im.save(out, "JPEG", **options)
bytes = out.tell()
out.seek(0)
im = Image.open(out)
im.bytes = bytes # for testing only
return im
def test_sanity(): def test_sanity(self):
# internal version number # internal version number
assert_match(Image.core.jpeglib_version, "\d+\.\d+$") self.assertRegexpMatches(Image.core.jpeglib_version, "\d+\.\d+$")
im = Image.open(test_file)
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "JPEG")
# --------------------------------------------------------------------
def test_app():
# Test APP/COM reader (@PIL135)
im = Image.open(test_file)
assert_equal(im.applist[0],
("APP0", b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"))
assert_equal(im.applist[1], ("COM", b"Python Imaging Library"))
assert_equal(len(im.applist), 2)
def test_cmyk():
# Test CMYK handling. Thanks to Tim and Charlie for test data,
# Michael for getting me to look one more time.
f = "Tests/images/pil_sample_cmyk.jpg"
im = Image.open(f)
# the source image has red pixels in the upper left corner.
c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]
assert_true(c == 0.0 and m > 0.8 and y > 0.8 and 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))]
assert_true(k > 0.9)
# roundtrip, and check again
im = roundtrip(im)
c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]
assert_true(c == 0.0 and m > 0.8 and y > 0.8 and k == 0.0)
c, m, y, k = [x / 255.0 for x in im.getpixel((im.size[0]-1, im.size[1]-1))]
assert_true(k > 0.9)
def test_dpi():
def test(xdpi, ydpi=None):
im = Image.open(test_file) im = Image.open(test_file)
im = roundtrip(im, dpi=(xdpi, ydpi or xdpi)) im.load()
return im.info.get("dpi") self.assertEqual(im.mode, "RGB")
assert_equal(test(72), (72, 72)) self.assertEqual(im.size, (128, 128))
assert_equal(test(300), (300, 300)) self.assertEqual(im.format, "JPEG")
assert_equal(test(100, 200), (100, 200))
assert_equal(test(0), None) # square pixels def test_app(self):
# Test APP/COM reader (@PIL135)
im = Image.open(test_file)
self.assertEqual(
im.applist[0],
("APP0", b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"))
self.assertEqual(im.applist[1], ("COM", b"Python Imaging Library"))
self.assertEqual(len(im.applist), 2)
def test_cmyk(self):
# Test CMYK handling. Thanks to Tim and Charlie for test data,
# Michael for getting me to look one more time.
f = "Tests/images/pil_sample_cmyk.jpg"
im = Image.open(f)
# the source image has red pixels in the upper left corner.
c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]
self.assertEqual(c, 0.0)
self.assertGreater(m, 0.8)
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))]
self.assertGreater(k, 0.9)
# roundtrip, and check again
im = self.roundtrip(im)
c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]
self.assertEqual(c, 0.0)
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))]
self.assertGreater(k, 0.9)
def test_dpi(self):
def test(xdpi, ydpi=None):
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))
self.assertEqual(test(0), None) # square pixels
def test_icc(self):
# Test ICC support
im1 = Image.open("Tests/images/rgb.jpg")
icc_profile = im1.info["icc_profile"]
self.assertEqual(len(icc_profile), 3144)
# Roundtrip via physical file.
f = self.tempfile("temp.jpg")
im1.save(f, icc_profile=icc_profile)
im2 = Image.open(f)
self.assertEqual(im2.info.get("icc_profile"), icc_profile)
# Roundtrip via memory buffer.
im1 = self.roundtrip(lena())
im2 = self.roundtrip(lena(), icc_profile=icc_profile)
self.assert_image_equal(im1, im2)
self.assertFalse(im1.info.get("icc_profile"))
self.assertTrue(im2.info.get("icc_profile"))
def test_icc_big(self):
# Make sure that the "extra" support handles large blocks
def test(n):
# 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]
assert len(icc_profile) == n # sanity
im1 = self.roundtrip(lena(), 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(ImageFile.MAXBLOCK) # full buffer block
test(ImageFile.MAXBLOCK+1) # full buffer block plus one byte
test(ImageFile.MAXBLOCK*4+3) # large block
def test_optimize(self):
im1 = self.roundtrip(lena())
im2 = self.roundtrip(lena(), optimize=1)
self.assert_image_equal(im1, im2)
self.assertGreaterEqual(im1.bytes, im2.bytes)
def test_optimize_large_buffer(self):
# https://github.com/python-pillow/Pillow/issues/148
f = self.tempfile('temp.jpg')
# this requires ~ 1.5x Image.MAXBLOCK
im = Image.new("RGB", (4096, 4096), 0xff3333)
im.save(f, format="JPEG", optimize=True)
def test_progressive(self):
im1 = self.roundtrip(lena())
im2 = self.roundtrip(lena(), progressive=True)
self.assert_image_equal(im1, im2)
self.assertGreaterEqual(im1.bytes, im2.bytes)
def test_progressive_large_buffer(self):
f = self.tempfile('temp.jpg')
# this requires ~ 1.5x Image.MAXBLOCK
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')
if py3:
a = bytes(random.randint(0, 255) for _ in range(256 * 256 * 3))
else:
a = b''.join(chr(random.randint(0, 255)) for _ in range(256 * 256 * 3))
im = Image.frombuffer("RGB", (256, 256), a, "raw", "RGB", 0, 1)
# this requires more bytes than pixels in the image
im.save(f, format="JPEG", progressive=True, quality=100)
def test_large_exif(self):
# https://github.com/python-pillow/Pillow/issues/148
f = self.tempfile('temp.jpg')
im = lena()
im.save(f, 'JPEG', quality=90, exif=b"1"*65532)
def test_progressive_compat(self):
im1 = self.roundtrip(lena())
im2 = self.roundtrip(lena(), progressive=1)
im3 = self.roundtrip(lena(), progression=1) # compatibility
self.assert_image_equal(im1, im2)
self.assert_image_equal(im1, im3)
self.assertFalse(im1.info.get("progressive"))
self.assertFalse(im1.info.get("progression"))
self.assertTrue(im2.info.get("progressive"))
self.assertTrue(im2.info.get("progression"))
self.assertTrue(im3.info.get("progressive"))
self.assertTrue(im3.info.get("progression"))
def test_quality(self):
im1 = self.roundtrip(lena())
im2 = self.roundtrip(lena(), quality=50)
self.assert_image(im1, im2.mode, im2.size)
self.assertGreaterEqual(im1.bytes, im2.bytes)
def test_smooth(self):
im1 = self.roundtrip(lena())
im2 = self.roundtrip(lena(), smooth=100)
self.assert_image(im1, im2.mode, im2.size)
def test_subsampling(self):
def getsampling(im):
layer = im.layer
return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]
# experimental API
im = self.roundtrip(lena(), subsampling=-1) # default
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
im = self.roundtrip(lena(), subsampling=0) # 4:4:4
self.assertEqual(getsampling(im), (1, 1, 1, 1, 1, 1))
im = self.roundtrip(lena(), subsampling=1) # 4:2:2
self.assertEqual(getsampling(im), (2, 1, 1, 1, 1, 1))
im = self.roundtrip(lena(), subsampling=2) # 4:1:1
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
im = self.roundtrip(lena(), subsampling=3) # default (undefined)
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
im = self.roundtrip(lena(), subsampling="4:4:4")
self.assertEqual(getsampling(im), (1, 1, 1, 1, 1, 1))
im = self.roundtrip(lena(), subsampling="4:2:2")
self.assertEqual(getsampling(im), (2, 1, 1, 1, 1, 1))
im = self.roundtrip(lena(), subsampling="4:1:1")
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
self.assertRaises(
TypeError, lambda: self.roundtrip(lena(), 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')
def test_quality_keep(self):
im = Image.open("Images/lena.jpg")
f = self.tempfile('temp.jpg')
im.save(f, quality='keep')
def test_junk_jpeg_header(self):
# https://github.com/python-pillow/Pillow/issues/630
filename = "Tests/images/junk_jpeg_header.jpg"
Image.open(filename)
def test_icc(): if __name__ == '__main__':
# Test ICC support unittest.main()
im1 = Image.open("Tests/images/rgb.jpg")
icc_profile = im1.info["icc_profile"]
assert_equal(len(icc_profile), 3144)
# Roundtrip via physical file.
f = tempfile("temp.jpg")
im1.save(f, icc_profile=icc_profile)
im2 = Image.open(f)
assert_equal(im2.info.get("icc_profile"), icc_profile)
# Roundtrip via memory buffer.
im1 = roundtrip(lena())
im2 = roundtrip(lena(), icc_profile=icc_profile)
assert_image_equal(im1, im2)
assert_false(im1.info.get("icc_profile"))
assert_true(im2.info.get("icc_profile"))
def test_icc_big():
# Make sure that the "extra" support handles large blocks
def test(n):
# 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]
assert len(icc_profile) == n # sanity
im1 = roundtrip(lena(), icc_profile=icc_profile)
assert_equal(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(ImageFile.MAXBLOCK) # full buffer block
test(ImageFile.MAXBLOCK+1) # full buffer block plus one byte
test(ImageFile.MAXBLOCK*4+3) # large block
def test_optimize():
im1 = roundtrip(lena())
im2 = roundtrip(lena(), optimize=1)
assert_image_equal(im1, im2)
assert_true(im1.bytes >= im2.bytes)
def test_optimize_large_buffer():
# https://github.com/python-pillow/Pillow/issues/148
f = tempfile('temp.jpg')
# this requires ~ 1.5x Image.MAXBLOCK
im = Image.new("RGB", (4096, 4096), 0xff3333)
im.save(f, format="JPEG", optimize=True)
def test_progressive():
im1 = roundtrip(lena())
im2 = roundtrip(lena(), progressive=True)
assert_image_equal(im1, im2)
assert_true(im1.bytes >= im2.bytes)
def test_progressive_large_buffer():
f = tempfile('temp.jpg')
# this requires ~ 1.5x Image.MAXBLOCK
im = Image.new("RGB", (4096, 4096), 0xff3333)
im.save(f, format="JPEG", progressive=True)
def test_progressive_large_buffer_highest_quality():
f = tempfile('temp.jpg')
if py3:
a = bytes(random.randint(0, 255) for _ in range(256 * 256 * 3))
else:
a = b''.join(chr(random.randint(0, 255)) for _ in range(256 * 256 * 3))
im = Image.frombuffer("RGB", (256, 256), a, "raw", "RGB", 0, 1)
# this requires more bytes than pixels in the image
im.save(f, format="JPEG", progressive=True, quality=100)
def test_large_exif():
# https://github.com/python-pillow/Pillow/issues/148
f = tempfile('temp.jpg')
im = lena()
im.save(f, 'JPEG', quality=90, exif=b"1"*65532)
def test_progressive_compat():
im1 = roundtrip(lena())
im2 = roundtrip(lena(), progressive=1)
im3 = roundtrip(lena(), progression=1) # compatibility
assert_image_equal(im1, im2)
assert_image_equal(im1, im3)
assert_false(im1.info.get("progressive"))
assert_false(im1.info.get("progression"))
assert_true(im2.info.get("progressive"))
assert_true(im2.info.get("progression"))
assert_true(im3.info.get("progressive"))
assert_true(im3.info.get("progression"))
def test_quality():
im1 = roundtrip(lena())
im2 = roundtrip(lena(), quality=50)
assert_image(im1, im2.mode, im2.size)
assert_true(im1.bytes >= im2.bytes)
def test_smooth():
im1 = roundtrip(lena())
im2 = roundtrip(lena(), smooth=100)
assert_image(im1, im2.mode, im2.size)
def test_subsampling():
def getsampling(im):
layer = im.layer
return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]
# experimental API
im = roundtrip(lena(), subsampling=-1) # default
assert_equal(getsampling(im), (2, 2, 1, 1, 1, 1))
im = roundtrip(lena(), subsampling=0) # 4:4:4
assert_equal(getsampling(im), (1, 1, 1, 1, 1, 1))
im = roundtrip(lena(), subsampling=1) # 4:2:2
assert_equal(getsampling(im), (2, 1, 1, 1, 1, 1))
im = roundtrip(lena(), subsampling=2) # 4:1:1
assert_equal(getsampling(im), (2, 2, 1, 1, 1, 1))
im = roundtrip(lena(), subsampling=3) # default (undefined)
assert_equal(getsampling(im), (2, 2, 1, 1, 1, 1))
im = roundtrip(lena(), subsampling="4:4:4")
assert_equal(getsampling(im), (1, 1, 1, 1, 1, 1))
im = roundtrip(lena(), subsampling="4:2:2")
assert_equal(getsampling(im), (2, 1, 1, 1, 1, 1))
im = roundtrip(lena(), subsampling="4:1:1")
assert_equal(getsampling(im), (2, 2, 1, 1, 1, 1))
assert_exception(TypeError, lambda: roundtrip(lena(), subsampling="1:1:1"))
def test_exif():
im = Image.open("Tests/images/pil_sample_rgb.jpg")
info = im._getexif()
assert_equal(info[305], 'Adobe Photoshop CS Macintosh')
def test_quality_keep():
im = Image.open("Images/lena.jpg")
f = tempfile('temp.jpg')
assert_no_exception(lambda: im.save(f, quality='keep'))
def test_junk_jpeg_header():
# https://github.com/python-pillow/Pillow/issues/630
filename = "Tests/images/junk_jpeg_header.jpg"
assert_no_exception(lambda: Image.open(filename))
# End of file # End of file

View File

@ -1,110 +1,114 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
from PIL import ImageFile from io import BytesIO
codecs = dir(Image.core) codecs = dir(Image.core)
if "jpeg2k_encoder" not in codecs or "jpeg2k_decoder" not in codecs:
skip('JPEG 2000 support not available')
# OpenJPEG 2.0.0 outputs this debugging message sometimes; we should
# ignore it---it doesn't represent a test failure.
ignore('Not enough memory to handle tile data')
test_card = Image.open('Tests/images/test-card.png') test_card = Image.open('Tests/images/test-card.png')
test_card.load() test_card.load()
def roundtrip(im, **options): # OpenJPEG 2.0.0 outputs this debugging message sometimes; we should
out = BytesIO() # ignore it---it doesn't represent a test failure.
im.save(out, "JPEG2000", **options) # 'Not enough memory to handle tile data'
bytes = out.tell()
out.seek(0)
im = Image.open(out)
im.bytes = bytes # for testing only
im.load()
return im
# ----------------------------------------------------------------------
def test_sanity(): class TestFileJpeg2k(PillowTestCase):
# Internal version number
assert_match(Image.core.jp2klib_version, '\d+\.\d+\.\d+$')
im = Image.open('Tests/images/test-card-lossless.jp2') def setUp(self):
im.load() if "jpeg2k_encoder" not in codecs or "jpeg2k_decoder" not in codecs:
assert_equal(im.mode, 'RGB') self.skipTest('JPEG 2000 support not available')
assert_equal(im.size, (640, 480))
assert_equal(im.format, 'JPEG2000')
# ----------------------------------------------------------------------
# These two test pre-written JPEG 2000 files that were not written with def roundtrip(self, im, **options):
# PIL (they were made using Adobe Photoshop) out = BytesIO()
im.save(out, "JPEG2000", **options)
bytes = out.tell()
out.seek(0)
im = Image.open(out)
im.bytes = bytes # for testing only
im.load()
return im
def test_lossless(): def test_sanity(self):
im = Image.open('Tests/images/test-card-lossless.jp2') # Internal version number
im.load() self.assertRegexpMatches(Image.core.jp2klib_version, '\d+\.\d+\.\d+$')
im.save('/tmp/test-card.png')
assert_image_similar(im, test_card, 1.0e-3)
def test_lossy_tiled(): im = Image.open('Tests/images/test-card-lossless.jp2')
im = Image.open('Tests/images/test-card-lossy-tiled.jp2') im.load()
im.load() self.assertEqual(im.mode, 'RGB')
assert_image_similar(im, test_card, 2.0) self.assertEqual(im.size, (640, 480))
self.assertEqual(im.format, 'JPEG2000')
# ---------------------------------------------------------------------- # These two test pre-written JPEG 2000 files that were not written with
# PIL (they were made using Adobe Photoshop)
def test_lossless_rt(): def test_lossless(self):
im = roundtrip(test_card) im = Image.open('Tests/images/test-card-lossless.jp2')
assert_image_equal(im, test_card) im.load()
im.save('/tmp/test-card.png')
self.assert_image_similar(im, test_card, 1.0e-3)
def test_lossy_rt(): def test_lossy_tiled(self):
im = roundtrip(test_card, quality_layers=[20]) im = Image.open('Tests/images/test-card-lossy-tiled.jp2')
assert_image_similar(im, test_card, 2.0) im.load()
self.assert_image_similar(im, test_card, 2.0)
def test_tiled_rt(): def test_lossless_rt(self):
im = roundtrip(test_card, tile_size=(128, 128)) im = self.roundtrip(test_card)
assert_image_equal(im, test_card) self.assert_image_equal(im, test_card)
def test_tiled_offset_rt(): def test_lossy_rt(self):
im = roundtrip(test_card, tile_size=(128, 128), tile_offset=(0, 0), im = self.roundtrip(test_card, quality_layers=[20])
offset=(32, 32)) self.assert_image_similar(im, test_card, 2.0)
assert_image_equal(im, test_card)
def test_irreversible_rt():
im = roundtrip(test_card, irreversible=True, quality_layers=[20])
assert_image_similar(im, test_card, 2.0)
def test_prog_qual_rt(): def test_tiled_rt(self):
im = roundtrip(test_card, quality_layers=[60, 40, 20], progression='LRCP') im = self.roundtrip(test_card, tile_size=(128, 128))
assert_image_similar(im, test_card, 2.0) self.assert_image_equal(im, test_card)
def test_prog_res_rt(): def test_tiled_offset_rt(self):
im = roundtrip(test_card, num_resolutions=8, progression='RLCP') im = self.roundtrip(
assert_image_equal(im, test_card) 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):
im = self.roundtrip(test_card, irreversible=True, quality_layers=[20])
self.assert_image_similar(im, test_card, 2.0)
def test_reduce(): def test_prog_qual_rt(self):
im = Image.open('Tests/images/test-card-lossless.jp2') im = self.roundtrip(
im.reduce = 2 test_card, quality_layers=[60, 40, 20], progression='LRCP')
im.load() self.assert_image_similar(im, test_card, 2.0)
assert_equal(im.size, (160, 120))
def test_layers(): def test_prog_res_rt(self):
out = BytesIO() im = self.roundtrip(test_card, num_resolutions=8, progression='RLCP')
test_card.save(out, 'JPEG2000', quality_layers=[100, 50, 10], self.assert_image_equal(im, test_card)
progression='LRCP')
out.seek(0)
im = Image.open(out)
im.layers = 1
im.load()
assert_image_similar(im, test_card, 13)
out.seek(0) def test_reduce(self):
im = Image.open(out) im = Image.open('Tests/images/test-card-lossless.jp2')
im.layers = 3 im.reduce = 2
im.load() im.load()
assert_image_similar(im, test_card, 0.4) self.assertEqual(im.size, (160, 120))
def test_layers(self):
out = BytesIO()
test_card.save(out, 'JPEG2000', quality_layers=[100, 50, 10],
progression='LRCP')
out.seek(0)
im = Image.open(out)
im.layers = 1
im.load()
self.assert_image_similar(im, test_card, 13)
out.seek(0)
im = Image.open(out)
im.layers = 3
im.load()
self.assert_image_similar(im, test_card, 0.4)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,300 +1,318 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena, py3
import os import os
from PIL import Image, TiffImagePlugin from PIL import Image, TiffImagePlugin
codecs = dir(Image.core)
if "libtiff_encoder" not in codecs or "libtiff_decoder" not in codecs: class TestFileLibTiff(PillowTestCase):
skip("tiff support not available")
def _assert_noerr(im): def setUp(self):
"""Helper tests that assert basic sanity about the g4 tiff reading""" codecs = dir(Image.core)
#1 bit
assert_equal(im.mode, "1")
# Does the data actually load if "libtiff_encoder" not in codecs or "libtiff_decoder" not in codecs:
assert_no_exception(lambda: im.load()) self.skipTest("tiff support not available")
assert_no_exception(lambda: im.getdata())
try: def _assert_noerr(self, im):
assert_equal(im._compression, 'group4') """Helper tests that assert basic sanity about the g4 tiff reading"""
except: # 1 bit
print("No _compression") self.assertEqual(im.mode, "1")
print (dir(im))
# can we write it back out, in a different form. # Does the data actually load
out = tempfile("temp.png") im.load()
assert_no_exception(lambda: im.save(out)) im.getdata()
def test_g4_tiff(): try:
"""Test the ordinary file path load path""" self.assertEqual(im._compression, 'group4')
except:
print("No _compression")
print (dir(im))
file = "Tests/images/lena_g4_500.tif" # can we write it back out, in a different form.
im = Image.open(file) out = self.tempfile("temp.png")
im.save(out)
assert_equal(im.size, (500,500)) def test_g4_tiff(self):
_assert_noerr(im) """Test the ordinary file path load path"""
def test_g4_large(): file = "Tests/images/lena_g4_500.tif"
file = "Tests/images/pport_g4.tif" im = Image.open(file)
im = Image.open(file)
_assert_noerr(im)
def test_g4_tiff_file(): self.assertEqual(im.size, (500, 500))
"""Testing the string load path""" self._assert_noerr(im)
file = "Tests/images/lena_g4_500.tif" def test_g4_large(self):
with open(file,'rb') as f: file = "Tests/images/pport_g4.tif"
im = Image.open(f) im = Image.open(file)
self._assert_noerr(im)
assert_equal(im.size, (500,500)) def test_g4_tiff_file(self):
_assert_noerr(im) """Testing the string load path"""
def test_g4_tiff_bytesio(): file = "Tests/images/lena_g4_500.tif"
"""Testing the stringio loading code path""" with open(file, 'rb') as f:
from io import BytesIO im = Image.open(f)
file = "Tests/images/lena_g4_500.tif"
s = BytesIO()
with open(file,'rb') as f:
s.write(f.read())
s.seek(0)
im = Image.open(s)
assert_equal(im.size, (500,500)) self.assertEqual(im.size, (500, 500))
_assert_noerr(im) self._assert_noerr(im)
def test_g4_eq_png(): def test_g4_tiff_bytesio(self):
""" Checking that we're actually getting the data that we expect""" """Testing the stringio loading code path"""
png = Image.open('Tests/images/lena_bw_500.png') from io import BytesIO
g4 = Image.open('Tests/images/lena_g4_500.tif') file = "Tests/images/lena_g4_500.tif"
s = BytesIO()
with open(file, 'rb') as f:
s.write(f.read())
s.seek(0)
im = Image.open(s)
assert_image_equal(g4, png) self.assertEqual(im.size, (500, 500))
self._assert_noerr(im)
# see https://github.com/python-pillow/Pillow/issues/279 def test_g4_eq_png(self):
def test_g4_fillorder_eq_png(): """ Checking that we're actually getting the data that we expect"""
""" Checking that we're actually getting the data that we expect""" png = Image.open('Tests/images/lena_bw_500.png')
png = Image.open('Tests/images/g4-fillorder-test.png') g4 = Image.open('Tests/images/lena_g4_500.tif')
g4 = Image.open('Tests/images/g4-fillorder-test.tif')
assert_image_equal(g4, png) self.assert_image_equal(g4, png)
def test_g4_write(): # see https://github.com/python-pillow/Pillow/issues/279
"""Checking to see that the saved image is the same as what we wrote""" def test_g4_fillorder_eq_png(self):
file = "Tests/images/lena_g4_500.tif" """ Checking that we're actually getting the data that we expect"""
orig = Image.open(file) png = Image.open('Tests/images/g4-fillorder-test.png')
g4 = Image.open('Tests/images/g4-fillorder-test.tif')
out = tempfile("temp.tif") self.assert_image_equal(g4, png)
rot = orig.transpose(Image.ROTATE_90)
assert_equal(rot.size,(500,500))
rot.save(out)
reread = Image.open(out) def test_g4_write(self):
assert_equal(reread.size,(500,500)) """Checking to see that the saved image is the same as what we wrote"""
_assert_noerr(reread) file = "Tests/images/lena_g4_500.tif"
assert_image_equal(reread, rot) orig = Image.open(file)
assert_equal(reread.info['compression'], 'group4')
assert_equal(reread.info['compression'], orig.info['compression']) out = self.tempfile("temp.tif")
rot = orig.transpose(Image.ROTATE_90)
self.assertEqual(rot.size, (500, 500))
rot.save(out)
assert_false(orig.tobytes() == reread.tobytes()) reread = Image.open(out)
self.assertEqual(reread.size, (500, 500))
self._assert_noerr(reread)
self.assert_image_equal(reread, rot)
self.assertEqual(reread.info['compression'], 'group4')
def test_adobe_deflate_tiff(): self.assertEqual(reread.info['compression'], orig.info['compression'])
file = "Tests/images/tiff_adobe_deflate.tif"
im = Image.open(file)
assert_equal(im.mode, "RGB") self.assertNotEqual(orig.tobytes(), reread.tobytes())
assert_equal(im.size, (278, 374))
assert_equal(im.tile[0][:3], ('tiff_adobe_deflate', (0, 0, 278, 374), 0))
assert_no_exception(lambda: im.load())
def test_write_metadata(): def test_adobe_deflate_tiff(self):
""" Test metadata writing through libtiff """ file = "Tests/images/tiff_adobe_deflate.tif"
img = Image.open('Tests/images/lena_g4.tif') im = Image.open(file)
f = tempfile('temp.tiff')
img.save(f, tiffinfo = img.tag) 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))
im.load()
loaded = Image.open(f) def test_write_metadata(self):
""" Test metadata writing through libtiff """
img = Image.open('Tests/images/lena_g4.tif')
f = self.tempfile('temp.tiff')
original = img.tag.named() img.save(f, tiffinfo=img.tag)
reloaded = loaded.tag.named()
# PhotometricInterpretation is set from SAVE_INFO, not the original image. loaded = Image.open(f)
ignored = ['StripByteCounts', 'RowsPerStrip', 'PageNumber', 'PhotometricInterpretation']
for tag, value in reloaded.items(): original = img.tag.named()
if tag not in ignored: reloaded = loaded.tag.named()
if tag.endswith('Resolution'):
val = original[tag]
assert_almost_equal(val[0][0]/val[0][1], value[0][0]/value[0][1],
msg="%s didn't roundtrip" % tag)
else:
assert_equal(original[tag], value, "%s didn't roundtrip" % tag)
for tag, value in original.items(): # PhotometricInterpretation is set from SAVE_INFO,
if tag not in ignored: # not the original image.
if tag.endswith('Resolution'): ignored = [
val = reloaded[tag] 'StripByteCounts', 'RowsPerStrip',
assert_almost_equal(val[0][0]/val[0][1], value[0][0]/value[0][1], 'PageNumber', 'PhotometricInterpretation']
msg="%s didn't roundtrip" % tag)
else:
assert_equal(value, reloaded[tag], "%s didn't roundtrip" % tag)
for tag, value in reloaded.items():
if tag not in ignored:
if tag.endswith('Resolution'):
val = original[tag]
self.assert_almost_equal(
val[0][0]/val[0][1], value[0][0]/value[0][1],
msg="%s didn't roundtrip" % tag)
else:
self.assertEqual(
original[tag], value, "%s didn't roundtrip" % tag)
def test_g3_compression(): for tag, value in original.items():
i = Image.open('Tests/images/lena_g4_500.tif') if tag not in ignored:
out = tempfile("temp.tif") if tag.endswith('Resolution'):
i.save(out, compression='group3') val = reloaded[tag]
self.assert_almost_equal(
val[0][0]/val[0][1], value[0][0]/value[0][1],
msg="%s didn't roundtrip" % tag)
else:
self.assertEqual(
value, reloaded[tag], "%s didn't roundtrip" % tag)
reread = Image.open(out) def test_g3_compression(self):
assert_equal(reread.info['compression'], 'group3') i = Image.open('Tests/images/lena_g4_500.tif')
assert_image_equal(reread, i) out = self.tempfile("temp.tif")
i.save(out, compression='group3')
def test_little_endian(): reread = Image.open(out)
im = Image.open('Tests/images/16bit.deflate.tif') self.assertEqual(reread.info['compression'], 'group3')
assert_equal(im.getpixel((0,0)), 480) self.assert_image_equal(reread, i)
assert_equal(im.mode, 'I;16')
b = im.tobytes() def test_little_endian(self):
# Bytes are in image native order (little endian) im = Image.open('Tests/images/16bit.deflate.tif')
if py3: self.assertEqual(im.getpixel((0, 0)), 480)
assert_equal(b[0], ord(b'\xe0')) self.assertEqual(im.mode, 'I;16')
assert_equal(b[1], ord(b'\x01'))
else:
assert_equal(b[0], b'\xe0')
assert_equal(b[1], b'\x01')
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'))
else:
self.assertEqual(b[0], b'\xe0')
self.assertEqual(b[1], b'\x01')
out = tempfile("temp.tif") out = self.tempfile("temp.tif")
#out = "temp.le.tif" # out = "temp.le.tif"
im.save(out) im.save(out)
reread = Image.open(out) reread = Image.open(out)
assert_equal(reread.info['compression'], im.info['compression']) self.assertEqual(reread.info['compression'], im.info['compression'])
assert_equal(reread.getpixel((0,0)), 480) self.assertEqual(reread.getpixel((0, 0)), 480)
# UNDONE - libtiff defaults to writing in native endian, so # UNDONE - libtiff defaults to writing in native endian, so
# on big endian, we'll get back mode = 'I;16B' here. # on big endian, we'll get back mode = 'I;16B' here.
def test_big_endian(): def test_big_endian(self):
im = Image.open('Tests/images/16bit.MM.deflate.tif') im = Image.open('Tests/images/16bit.MM.deflate.tif')
assert_equal(im.getpixel((0,0)), 480) self.assertEqual(im.getpixel((0, 0)), 480)
assert_equal(im.mode, 'I;16B') self.assertEqual(im.mode, 'I;16B')
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (big endian) # Bytes are in image native order (big endian)
if py3: if py3:
assert_equal(b[0], ord(b'\x01')) self.assertEqual(b[0], ord(b'\x01'))
assert_equal(b[1], ord(b'\xe0')) self.assertEqual(b[1], ord(b'\xe0'))
else: else:
assert_equal(b[0], b'\x01') self.assertEqual(b[0], b'\x01')
assert_equal(b[1], b'\xe0') self.assertEqual(b[1], b'\xe0')
out = tempfile("temp.tif") out = self.tempfile("temp.tif")
im.save(out) im.save(out)
reread = Image.open(out) reread = Image.open(out)
assert_equal(reread.info['compression'], im.info['compression']) self.assertEqual(reread.info['compression'], im.info['compression'])
assert_equal(reread.getpixel((0,0)), 480) self.assertEqual(reread.getpixel((0, 0)), 480)
def test_g4_string_info(): def test_g4_string_info(self):
"""Tests String data in info directory""" """Tests String data in info directory"""
file = "Tests/images/lena_g4_500.tif" file = "Tests/images/lena_g4_500.tif"
orig = Image.open(file) orig = Image.open(file)
out = tempfile("temp.tif") out = self.tempfile("temp.tif")
orig.tag[269] = 'temp.tif' orig.tag[269] = 'temp.tif'
orig.save(out) orig.save(out)
reread = Image.open(out) reread = Image.open(out)
assert_equal('temp.tif', reread.tag[269]) self.assertEqual('temp.tif', reread.tag[269])
def test_12bit_rawmode(): def test_12bit_rawmode(self):
""" Are we generating the same interpretation of the image as Imagemagick is? """ """ Are we generating the same interpretation
TiffImagePlugin.READ_LIBTIFF = True of the image as Imagemagick is? """
#Image.DEBUG = True TiffImagePlugin.READ_LIBTIFF = True
im = Image.open('Tests/images/12bit.cropped.tif') # Image.DEBUG = True
im.load() im = Image.open('Tests/images/12bit.cropped.tif')
TiffImagePlugin.READ_LIBTIFF = False im.load()
# to make the target -- TiffImagePlugin.READ_LIBTIFF = False
# convert 12bit.cropped.tif -depth 16 tmp.tif # to make the target --
# convert tmp.tif -evaluate RightShift 4 12in16bit2.tif # convert 12bit.cropped.tif -depth 16 tmp.tif
# imagemagick will auto scale so that a 12bit FFF is 16bit FFF0, # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif
# so we need to unshift so that the integer values are the same. # 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.
im2 = Image.open('Tests/images/12in16bit.tif') im2 = Image.open('Tests/images/12in16bit.tif')
if Image.DEBUG: if Image.DEBUG:
print (im.getpixel((0,0))) print (im.getpixel((0, 0)))
print (im.getpixel((0,1))) print (im.getpixel((0, 1)))
print (im.getpixel((0,2))) print (im.getpixel((0, 2)))
print (im2.getpixel((0,0))) print (im2.getpixel((0, 0)))
print (im2.getpixel((0,1))) print (im2.getpixel((0, 1)))
print (im2.getpixel((0,2))) print (im2.getpixel((0, 2)))
assert_image_equal(im, im2) self.assert_image_equal(im, im2)
def test_blur(): def test_blur(self):
# test case from irc, how to do blur on b/w image and save to compressed tif. # test case from irc, how to do blur on b/w image
from PIL import ImageFilter # and save to compressed tif.
out = tempfile('temp.tif') from PIL import ImageFilter
im = Image.open('Tests/images/pport_g4.tif') out = self.tempfile('temp.tif')
im = im.convert('L') im = Image.open('Tests/images/pport_g4.tif')
im = im.convert('L')
im=im.filter(ImageFilter.GaussianBlur(4)) im = im.filter(ImageFilter.GaussianBlur(4))
im.save(out, compression='tiff_adobe_deflate') im.save(out, compression='tiff_adobe_deflate')
im2 = Image.open(out)
im2.load()
assert_image_equal(im, im2)
def test_compressions():
im = lena('RGB')
out = tempfile('temp.tif')
for compression in ('packbits', 'tiff_lzw'):
im.save(out, compression=compression)
im2 = Image.open(out) im2 = Image.open(out)
assert_image_equal(im, im2) im2.load()
im.save(out, compression='jpeg') self.assert_image_equal(im, im2)
im2 = Image.open(out)
assert_image_similar(im, im2, 30) def test_compressions(self):
im = lena('RGB')
out = self.tempfile('temp.tif')
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')
im2 = Image.open(out)
self.assert_image_similar(im, im2, 30)
def test_cmyk_save(self):
im = lena('CMYK')
out = self.tempfile('temp.tif')
im.save(out, compression='tiff_adobe_deflate')
im2 = Image.open(out)
self.assert_image_equal(im, im2)
def xtest_bw_compression_wRGB(self):
""" This test passes, but when running all tests causes a failure due
to output on stderr from the error thrown by libtiff. We need to
capture that but not now"""
im = lena('RGB')
out = self.tempfile('temp.tif')
self.assertRaises(
IOError, lambda: im.save(out, compression='tiff_ccitt'))
self.assertRaises(IOError, lambda: im.save(out, compression='group3'))
self.assertRaises(IOError, lambda: im.save(out, compression='group4'))
def test_fp_leak(self):
im = Image.open("Tests/images/lena_g4_500.tif")
fn = im.fp.fileno()
os.fstat(fn)
im.load() # this should close it.
self.assertRaises(OSError, lambda: os.fstat(fn))
im = None # this should force even more closed.
self.assertRaises(OSError, lambda: os.fstat(fn))
self.assertRaises(OSError, lambda: os.close(fn))
def test_cmyk_save(): if __name__ == '__main__':
im = lena('CMYK') unittest.main()
out = tempfile('temp.tif')
im.save(out, compression='tiff_adobe_deflate') # End of file
im2 = Image.open(out)
assert_image_equal(im, im2)
def xtest_bw_compression_wRGB():
""" This test passes, but when running all tests causes a failure due to
output on stderr from the error thrown by libtiff. We need to capture that
but not now"""
im = lena('RGB')
out = tempfile('temp.tif')
assert_exception(IOError, lambda: im.save(out, compression='tiff_ccitt'))
assert_exception(IOError, lambda: im.save(out, compression='group3'))
assert_exception(IOError, lambda: im.save(out, compression='group4'))
def test_fp_leak():
im = Image.open("Tests/images/lena_g4_500.tif")
fn = im.fp.fileno()
assert_no_exception(lambda: os.fstat(fn))
im.load() # this should close it.
assert_exception(OSError, lambda: os.fstat(fn))
im = None # this should force even more closed.
assert_exception(OSError, lambda: os.fstat(fn))
assert_exception(OSError, lambda: os.close(fn))

View File

@ -1,52 +1,56 @@
from tester import * from helper import unittest, tearDownModule
from PIL import Image from PIL import Image
from test_file_libtiff import _assert_noerr from test_file_libtiff import TestFileLibTiff
codecs = dir(Image.core)
if "libtiff_encoder" not in codecs or "libtiff_decoder" not in codecs:
skip("tiff support not available")
""" The small lena image was failing on open in the libtiff
decoder because the file pointer was set to the wrong place
by a spurious seek. It wasn't failing with the byteio method.
It was fixed by forcing an lseek to the beginning of the
file just before reading in libtiff. These tests remain
to ensure that it stays fixed. """
def test_g4_lena_file(): class TestFileLibTiffSmall(TestFileLibTiff):
"""Testing the open file load path"""
file = "Tests/images/lena_g4.tif" # Inherits TestFileLibTiff's setUp() and self._assert_noerr()
with open(file,'rb') as f:
im = Image.open(f)
assert_equal(im.size, (128,128)) """ The small lena image was failing on open in the libtiff
_assert_noerr(im) decoder because the file pointer was set to the wrong place
by a spurious seek. It wasn't failing with the byteio method.
def test_g4_lena_bytesio(): It was fixed by forcing an lseek to the beginning of the
"""Testing the bytesio loading code path""" file just before reading in libtiff. These tests remain
from io import BytesIO to ensure that it stays fixed. """
file = "Tests/images/lena_g4.tif"
s = BytesIO()
with open(file,'rb') as f:
s.write(f.read())
s.seek(0)
im = Image.open(s)
assert_equal(im.size, (128,128)) def test_g4_lena_file(self):
_assert_noerr(im) """Testing the open file load path"""
def test_g4_lena(): file = "Tests/images/lena_g4.tif"
"""The 128x128 lena image fails for some reason. Investigating""" with open(file, 'rb') as f:
im = Image.open(f)
file = "Tests/images/lena_g4.tif" self.assertEqual(im.size, (128, 128))
im = Image.open(file) self._assert_noerr(im)
assert_equal(im.size, (128,128)) def test_g4_lena_bytesio(self):
_assert_noerr(im) """Testing the bytesio loading code path"""
from io import BytesIO
file = "Tests/images/lena_g4.tif"
s = BytesIO()
with open(file, 'rb') as f:
s.write(f.read())
s.seek(0)
im = Image.open(s)
self.assertEqual(im.size, (128, 128))
self._assert_noerr(im)
def test_g4_lena(self):
"""The 128x128 lena image fails for some reason. Investigating"""
file = "Tests/images/lena_g4.tif"
im = Image.open(file)
self.assertEqual(im.size, (128, 128))
self._assert_noerr(im)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,15 +1,24 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_sanity():
file = tempfile("temp.msp") class TestFileMsp(PillowTestCase):
lena("1").save(file) def test_sanity(self):
im = Image.open(file) file = self.tempfile("temp.msp")
im.load()
assert_equal(im.mode, "1") lena("1").save(file)
assert_equal(im.size, (128, 128))
assert_equal(im.format, "MSP") im = Image.open(file)
im.load()
self.assertEqual(im.mode, "1")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "MSP")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,40 +1,47 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def _roundtrip(im): class TestFilePcx(PillowTestCase):
f = tempfile("temp.pcx")
im.save(f)
im2 = Image.open(f)
assert_equal(im2.mode, im.mode) def _roundtrip(self, im):
assert_equal(im2.size, im.size) f = self.tempfile("temp.pcx")
assert_equal(im2.format, "PCX") im.save(f)
assert_image_equal(im2, im) im2 = Image.open(f)
def test_sanity():
for mode in ('1', 'L', 'P', 'RGB'):
_roundtrip(lena(mode))
def test_odd(): self.assertEqual(im2.mode, im.mode)
# see issue #523, odd sized images should have a stride that's even. self.assertEqual(im2.size, im.size)
# not that imagemagick or gimp write pcx that way. self.assertEqual(im2.format, "PCX")
# we were not handling properly. self.assert_image_equal(im2, im)
for mode in ('1', 'L', 'P', 'RGB'):
# larger, odd sized images are better here to ensure that
# we handle interrupted scan lines properly.
_roundtrip(lena(mode).resize((511,511)))
def test_pil184(): def test_sanity(self):
# Check reading of files where xmin/xmax is not zero. for mode in ('1', 'L', 'P', 'RGB'):
self._roundtrip(lena(mode))
file = "Tests/images/pil184.pcx" def test_odd(self):
im = Image.open(file) # 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'):
# larger, odd sized images are better here to ensure that
# we handle interrupted scan lines properly.
self._roundtrip(lena(mode).resize((511, 511)))
assert_equal(im.size, (447, 144)) def test_pil184(self):
assert_equal(im.tile[0][1], (0, 0, 447, 144)) # Check reading of files where xmin/xmax is not zero.
# Make sure all pixels are either 0 or 255. file = "Tests/images/pil184.pcx"
assert_equal(im.histogram()[0] + im.histogram()[255], 447*144) im = Image.open(file)
self.assertEqual(im.size, (447, 144))
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)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,58 +1,59 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
import os.path import os.path
def helper_save_as_pdf(mode): class TestFilePdf(PillowTestCase):
# Arrange
im = lena(mode)
outfile = tempfile("temp_" + mode + ".pdf")
# Act def helper_save_as_pdf(self, mode):
im.save(outfile) # Arrange
im = lena(mode)
outfile = self.tempfile("temp_" + mode + ".pdf")
# Assert # Act
assert_true(os.path.isfile(outfile)) im.save(outfile)
assert_greater(os.path.getsize(outfile), 0)
# Assert
self.assertTrue(os.path.isfile(outfile))
self.assertGreater(os.path.getsize(outfile), 0)
def test_monochrome(self):
# Arrange
mode = "1"
# Act / Assert
self.helper_save_as_pdf(mode)
def test_greyscale(self):
# Arrange
mode = "L"
# Act / Assert
self.helper_save_as_pdf(mode)
def test_rgb(self):
# Arrange
mode = "RGB"
# Act / Assert
self.helper_save_as_pdf(mode)
def test_p_mode(self):
# Arrange
mode = "P"
# Act / Assert
self.helper_save_as_pdf(mode)
def test_cmyk_mode(self):
# Arrange
mode = "CMYK"
# Act / Assert
self.helper_save_as_pdf(mode)
def test_monochrome(): if __name__ == '__main__':
# Arrange unittest.main()
mode = "1"
# Act / Assert
helper_save_as_pdf(mode)
def test_greyscale():
# Arrange
mode = "L"
# Act / Assert
helper_save_as_pdf(mode)
def test_rgb():
# Arrange
mode = "RGB"
# Act / Assert
helper_save_as_pdf(mode)
def test_p_mode():
# Arrange
mode = "P"
# Act / Assert
helper_save_as_pdf(mode)
def test_cmyk_mode():
# Arrange
mode = "CMYK"
# Act / Assert
helper_save_as_pdf(mode)
# End of file # End of file

View File

@ -1,4 +1,6 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from io import BytesIO
from PIL import Image from PIL import Image
from PIL import PngImagePlugin from PIL import PngImagePlugin
@ -6,9 +8,6 @@ import zlib
codecs = dir(Image.core) codecs = dir(Image.core)
if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
skip("zip/deflate support not available")
# sample png stream # sample png stream
file = "Images/lena.png" file = "Images/lena.png"
@ -18,6 +17,7 @@ data = open(file, "rb").read()
MAGIC = PngImagePlugin._MAGIC MAGIC = PngImagePlugin._MAGIC
def chunk(cid, *data): def chunk(cid, *data):
file = BytesIO() file = BytesIO()
PngImagePlugin.putchunk(*(file, cid) + data) PngImagePlugin.putchunk(*(file, cid) + data)
@ -32,256 +32,268 @@ IEND = chunk(b"IEND")
HEAD = MAGIC + IHDR HEAD = MAGIC + IHDR
TAIL = IDAT + IEND TAIL = IDAT + IEND
def load(data): def load(data):
return Image.open(BytesIO(data)) return Image.open(BytesIO(data))
def roundtrip(im, **options): def roundtrip(im, **options):
out = BytesIO() out = BytesIO()
im.save(out, "PNG", **options) im.save(out, "PNG", **options)
out.seek(0) out.seek(0)
return Image.open(out) return Image.open(out)
# --------------------------------------------------------------------
def test_sanity(): class TestFilePng(PillowTestCase):
# internal version number def setUp(self):
assert_match(Image.core.zlib_version, "\d+\.\d+\.\d+(\.\d+)?$") if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
self.skipTest("zip/deflate support not available")
file = tempfile("temp.png") def test_sanity(self):
lena("RGB").save(file) # internal version number
self.assertRegexpMatches(
Image.core.zlib_version, "\d+\.\d+\.\d+(\.\d+)?$")
im = Image.open(file) file = self.tempfile("temp.png")
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "PNG")
lena("1").save(file) lena("RGB").save(file)
im = Image.open(file)
lena("L").save(file) im = Image.open(file)
im = Image.open(file) im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "PNG")
lena("P").save(file) lena("1").save(file)
im = Image.open(file) im = Image.open(file)
lena("RGB").save(file) lena("L").save(file)
im = Image.open(file) im = Image.open(file)
lena("I").save(file) lena("P").save(file)
im = Image.open(file) im = Image.open(file)
# -------------------------------------------------------------------- lena("RGB").save(file)
im = Image.open(file)
def test_broken(): lena("I").save(file)
# Check reading of totally broken files. In this case, the test im = Image.open(file)
# file was checked into Subversion as a text file.
file = "Tests/images/broken.png" def test_broken(self):
assert_exception(IOError, lambda: Image.open(file)) # Check reading of totally broken files. In this case, the test
# file was checked into Subversion as a text file.
def test_bad_text(): file = "Tests/images/broken.png"
# Make sure PIL can read malformed tEXt chunks (@PIL152) self.assertRaises(IOError, lambda: Image.open(file))
im = load(HEAD + chunk(b'tEXt') + TAIL) def test_bad_text(self):
assert_equal(im.info, {}) # Make sure PIL can read malformed tEXt chunks (@PIL152)
im = load(HEAD + chunk(b'tEXt', b'spam') + TAIL) im = load(HEAD + chunk(b'tEXt') + TAIL)
assert_equal(im.info, {'spam': ''}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'tEXt', b'spam\0') + TAIL) im = load(HEAD + chunk(b'tEXt', b'spam') + TAIL)
assert_equal(im.info, {'spam': ''}) self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b'tEXt', b'spam\0egg') + TAIL) im = load(HEAD + chunk(b'tEXt', b'spam\0') + TAIL)
assert_equal(im.info, {'spam': 'egg'}) self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b'tEXt', b'spam\0egg\0') + TAIL) im = load(HEAD + chunk(b'tEXt', b'spam\0egg') + TAIL)
assert_equal(im.info, {'spam': 'egg\x00'}) self.assertEqual(im.info, {'spam': 'egg'})
def test_bad_ztxt(): im = load(HEAD + chunk(b'tEXt', b'spam\0egg\0') + TAIL)
# Test reading malformed zTXt chunks (python-pillow/Pillow#318) self.assertEqual(im.info, {'spam': 'egg\x00'})
im = load(HEAD + chunk(b'zTXt') + TAIL) def test_bad_ztxt(self):
assert_equal(im.info, {}) # Test reading malformed zTXt chunks (python-pillow/Pillow#318)
im = load(HEAD + chunk(b'zTXt', b'spam') + TAIL) im = load(HEAD + chunk(b'zTXt') + TAIL)
assert_equal(im.info, {'spam': ''}) self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'zTXt', b'spam\0') + TAIL) im = load(HEAD + chunk(b'zTXt', b'spam') + TAIL)
assert_equal(im.info, {'spam': ''}) self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b'zTXt', b'spam\0\0') + TAIL) im = load(HEAD + chunk(b'zTXt', b'spam\0') + TAIL)
assert_equal(im.info, {'spam': ''}) self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b'zTXt', b'spam\0\0' + zlib.compress(b'egg')[:1]) + TAIL) im = load(HEAD + chunk(b'zTXt', b'spam\0\0') + TAIL)
assert_equal(im.info, {'spam': ''}) self.assertEqual(im.info, {'spam': ''})
im = load(HEAD + chunk(b'zTXt', b'spam\0\0' + zlib.compress(b'egg')) + TAIL) im = load(HEAD + chunk(
assert_equal(im.info, {'spam': 'egg'}) b'zTXt', b'spam\0\0' + zlib.compress(b'egg')[:1]) + TAIL)
self.assertEqual(im.info, {'spam': ''})
def test_interlace(): im = load(
HEAD + chunk(b'zTXt', b'spam\0\0' + zlib.compress(b'egg')) + TAIL)
self.assertEqual(im.info, {'spam': 'egg'})
file = "Tests/images/pil123p.png" def test_interlace(self):
im = Image.open(file)
assert_image(im, "P", (162, 150)) file = "Tests/images/pil123p.png"
assert_true(im.info.get("interlace")) im = Image.open(file)
assert_no_exception(lambda: im.load()) self.assert_image(im, "P", (162, 150))
self.assertTrue(im.info.get("interlace"))
file = "Tests/images/pil123rgba.png" im.load()
im = Image.open(file)
assert_image(im, "RGBA", (162, 150)) file = "Tests/images/pil123rgba.png"
assert_true(im.info.get("interlace")) im = Image.open(file)
assert_no_exception(lambda: im.load()) self.assert_image(im, "RGBA", (162, 150))
self.assertTrue(im.info.get("interlace"))
def test_load_transparent_p(): im.load()
file = "Tests/images/pil123p.png"
im = Image.open(file)
assert_image(im, "P", (162, 150)) def test_load_transparent_p(self):
im = im.convert("RGBA") file = "Tests/images/pil123p.png"
assert_image(im, "RGBA", (162, 150)) im = Image.open(file)
# image has 124 uniqe qlpha values self.assert_image(im, "P", (162, 150))
assert_equal(len(im.split()[3].getcolors()), 124) im = im.convert("RGBA")
self.assert_image(im, "RGBA", (162, 150))
def test_load_transparent_rgb(): # image has 124 uniqe qlpha values
file = "Tests/images/rgb_trns.png" self.assertEqual(len(im.split()[3].getcolors()), 124)
im = Image.open(file)
assert_image(im, "RGB", (64, 64)) def test_load_transparent_rgb(self):
im = im.convert("RGBA") file = "Tests/images/rgb_trns.png"
assert_image(im, "RGBA", (64, 64)) im = Image.open(file)
# image has 876 transparent pixels self.assert_image(im, "RGB", (64, 64))
assert_equal(im.split()[3].getcolors()[0][0], 876) im = im.convert("RGBA")
self.assert_image(im, "RGBA", (64, 64))
def test_save_p_transparent_palette(): # image has 876 transparent pixels
in_file = "Tests/images/pil123p.png" self.assertEqual(im.split()[3].getcolors()[0][0], 876)
im = Image.open(in_file)
file = tempfile("temp.png") def test_save_p_transparent_palette(self):
assert_no_exception(lambda: im.save(file)) in_file = "Tests/images/pil123p.png"
im = Image.open(in_file)
def test_save_p_single_transparency(): file = self.tempfile("temp.png")
in_file = "Tests/images/p_trns_single.png" im.save(file)
im = Image.open(in_file)
file = tempfile("temp.png") def test_save_p_single_transparency(self):
assert_no_exception(lambda: im.save(file)) in_file = "Tests/images/p_trns_single.png"
im = Image.open(in_file)
def test_save_l_transparency(): file = self.tempfile("temp.png")
in_file = "Tests/images/l_trns.png" im.save(file)
im = Image.open(in_file)
file = tempfile("temp.png") def test_save_l_transparency(self):
assert_no_exception(lambda: im.save(file)) in_file = "Tests/images/l_trns.png"
im = Image.open(in_file)
# There are 559 transparent pixels. file = self.tempfile("temp.png")
im = im.convert('RGBA') im.save(file)
assert_equal(im.split()[3].getcolors()[0][0], 559)
def test_save_rgb_single_transparency(): # There are 559 transparent pixels.
in_file = "Tests/images/caption_6_33_22.png" im = im.convert('RGBA')
im = Image.open(in_file) self.assertEqual(im.split()[3].getcolors()[0][0], 559)
file = tempfile("temp.png") def test_save_rgb_single_transparency(self):
assert_no_exception(lambda: im.save(file)) in_file = "Tests/images/caption_6_33_22.png"
im = Image.open(in_file)
def test_load_verify(): file = self.tempfile("temp.png")
# Check open/load/verify exception (@PIL150) im.save(file)
im = Image.open("Images/lena.png") def test_load_verify(self):
assert_no_exception(lambda: im.verify()) # Check open/load/verify exception (@PIL150)
im = Image.open("Images/lena.png") im = Image.open("Images/lena.png")
im.load() im.verify()
assert_exception(RuntimeError, lambda: im.verify())
def test_roundtrip_dpi(): im = Image.open("Images/lena.png")
# Check dpi roundtripping im.load()
self.assertRaises(RuntimeError, lambda: im.verify())
im = Image.open(file) def test_roundtrip_dpi(self):
# Check dpi roundtripping
im = roundtrip(im, dpi=(100, 100)) im = Image.open(file)
assert_equal(im.info["dpi"], (100, 100))
def test_roundtrip_text(): im = roundtrip(im, dpi=(100, 100))
# Check text roundtripping self.assertEqual(im.info["dpi"], (100, 100))
im = Image.open(file) def test_roundtrip_text(self):
# Check text roundtripping
info = PngImagePlugin.PngInfo() im = Image.open(file)
info.add_text("TXT", "VALUE")
info.add_text("ZIP", "VALUE", 1)
im = roundtrip(im, pnginfo=info) info = PngImagePlugin.PngInfo()
assert_equal(im.info, {'TXT': 'VALUE', 'ZIP': 'VALUE'}) info.add_text("TXT", "VALUE")
assert_equal(im.text, {'TXT': 'VALUE', 'ZIP': 'VALUE'}) info.add_text("ZIP", "VALUE", 1)
def test_scary(): im = roundtrip(im, pnginfo=info)
# Check reading of evil PNG file. For information, see: self.assertEqual(im.info, {'TXT': 'VALUE', 'ZIP': 'VALUE'})
# http://scary.beasts.org/security/CESA-2004-001.txt self.assertEqual(im.text, {'TXT': 'VALUE', 'ZIP': 'VALUE'})
# 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: def test_scary(self):
data = b'\x89' + fd.read() # Check reading of evil PNG file. For information, see:
# http://scary.beasts.org/security/CESA-2004-001.txt
# The first byte is removed from pngtest_bad.png
# to avoid classification as malware.
pngfile = BytesIO(data) with open("Tests/images/pngtest_bad.png.bin", 'rb') as fd:
assert_exception(IOError, lambda: Image.open(pngfile)) data = b'\x89' + fd.read()
def test_trns_rgb(): pngfile = BytesIO(data)
# Check writing and reading of tRNS chunks for RGB images. self.assertRaises(IOError, lambda: Image.open(pngfile))
# Independent file sample provided by Sebastian Spaeth.
file = "Tests/images/caption_6_33_22.png" def test_trns_rgb(self):
im = Image.open(file) # Check writing and reading of tRNS chunks for RGB images.
assert_equal(im.info["transparency"], (248, 248, 248)) # Independent file sample provided by Sebastian Spaeth.
# check saving transparency by default file = "Tests/images/caption_6_33_22.png"
im = roundtrip(im) im = Image.open(file)
assert_equal(im.info["transparency"], (248, 248, 248)) self.assertEqual(im.info["transparency"], (248, 248, 248))
im = roundtrip(im, transparency=(0, 1, 2)) # check saving transparency by default
assert_equal(im.info["transparency"], (0, 1, 2)) im = roundtrip(im)
self.assertEqual(im.info["transparency"], (248, 248, 248))
def test_trns_p(): im = roundtrip(im, transparency=(0, 1, 2))
# Check writing a transparency of 0, issue #528 self.assertEqual(im.info["transparency"], (0, 1, 2))
im = lena('P')
im.info['transparency']=0
f = tempfile("temp.png") def test_trns_p(self):
im.save(f) # Check writing a transparency of 0, issue #528
im = lena('P')
im.info['transparency'] = 0
im2 = Image.open(f) f = self.tempfile("temp.png")
assert_true('transparency' in im2.info) im.save(f)
assert_image_equal(im2.convert('RGBA'), im.convert('RGBA')) im2 = Image.open(f)
self.assertIn('transparency', im2.info)
self.assert_image_equal(im2.convert('RGBA'), im.convert('RGBA'))
def test_save_icc_profile_none(): def test_save_icc_profile_none(self):
# check saving files with an ICC profile set to None (omit profile) # check saving files with an ICC profile set to None (omit profile)
in_file = "Tests/images/icc_profile_none.png" in_file = "Tests/images/icc_profile_none.png"
im = Image.open(in_file) im = Image.open(in_file)
assert_equal(im.info['icc_profile'], None) self.assertEqual(im.info['icc_profile'], None)
im = roundtrip(im) im = roundtrip(im)
assert_false('icc_profile' in im.info) self.assertNotIn('icc_profile', im.info)
def test_roundtrip_icc_profile(): def test_roundtrip_icc_profile(self):
# check that we can roundtrip the icc profile # check that we can roundtrip the icc profile
im = lena('RGB') im = lena('RGB')
jpeg_image = Image.open('Tests/images/flower2.jpg') jpeg_image = Image.open('Tests/images/flower2.jpg')
expected_icc = jpeg_image.info['icc_profile'] expected_icc = jpeg_image.info['icc_profile']
im.info['icc_profile'] = expected_icc im.info['icc_profile'] = expected_icc
im = roundtrip(im) im = roundtrip(im)
assert_equal(im.info['icc_profile'], expected_icc) self.assertEqual(im.info['icc_profile'], expected_icc)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
@ -6,31 +6,37 @@ from PIL import Image
file = "Images/lena.ppm" file = "Images/lena.ppm"
data = open(file, "rb").read() data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "PPM")
def test_16bit_pgm(): class TestFilePpm(PillowTestCase):
im = Image.open('Tests/images/16_bit_binary.pgm')
im.load()
assert_equal(im.mode, 'I')
assert_equal(im.size, (20,100))
tgt = Image.open('Tests/images/16_bit_binary_pgm.png') def test_sanity(self):
assert_image_equal(im, tgt) im = Image.open(file)
im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "PPM")
def test_16bit_pgm(self):
im = Image.open('Tests/images/16_bit_binary.pgm')
im.load()
self.assertEqual(im.mode, 'I')
self.assertEqual(im.size, (20, 100))
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.load()
f = self.tempfile('temp.pgm')
im.save(f, 'PPM')
reloaded = Image.open(f)
self.assert_image_equal(im, reloaded)
def test_16bit_pgm_write(): if __name__ == '__main__':
im = Image.open('Tests/images/16_bit_binary.pgm') unittest.main()
im.load()
f = tempfile('temp.pgm')
assert_no_exception(lambda: im.save(f, 'PPM'))
reloaded = Image.open(f)
assert_image_equal(im, reloaded)
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
@ -6,9 +6,18 @@ from PIL import Image
file = "Images/lena.psd" file = "Images/lena.psd"
data = open(file, "rb").read() data = open(file, "rb").read()
def test_sanity():
im = Image.open(file) class TestImagePsd(PillowTestCase):
im.load()
assert_equal(im.mode, "RGB") def test_sanity(self):
assert_equal(im.size, (128, 128)) im = Image.open(file)
assert_equal(im.format, "PSD") im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "PSD")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
from PIL import SpiderImagePlugin from PIL import SpiderImagePlugin
@ -6,31 +6,34 @@ from PIL import SpiderImagePlugin
test_file = "Tests/images/lena.spider" test_file = "Tests/images/lena.spider"
def test_sanity(): class TestImageSpider(PillowTestCase):
im = Image.open(test_file)
im.load() def test_sanity(self):
assert_equal(im.mode, "F") im = Image.open(test_file)
assert_equal(im.size, (128, 128)) im.load()
assert_equal(im.format, "SPIDER") self.assertEqual(im.mode, "F")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "SPIDER")
def test_save(self):
# Arrange
temp = self.tempfile('temp.spider')
im = lena()
# Act
im.save(temp, "SPIDER")
# Assert
im2 = Image.open(temp)
self.assertEqual(im2.mode, "F")
self.assertEqual(im2.size, (128, 128))
self.assertEqual(im2.format, "SPIDER")
def test_isSpiderImage(self):
self.assertTrue(SpiderImagePlugin.isSpiderImage(test_file))
def test_save(): if __name__ == '__main__':
# Arrange unittest.main()
temp = tempfile('temp.spider')
im = lena()
# Act
im.save(temp, "SPIDER")
# Assert
im2 = Image.open(temp)
assert_equal(im2.mode, "F")
assert_equal(im2.size, (128, 128))
assert_equal(im2.format, "SPIDER")
def test_isSpiderImage():
assert_true(SpiderImagePlugin.isSpiderImage(test_file))
# End of file # End of file

View File

@ -1,28 +1,38 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image, TarIO from PIL import Image, TarIO
codecs = dir(Image.core) codecs = dir(Image.core)
if "zip_decoder" not in codecs and "jpeg_decoder" not in codecs:
skip("neither jpeg nor zip support not available")
# sample ppm stream # sample ppm stream
tarfile = "Images/lena.tar" tarfile = "Images/lena.tar"
def test_sanity():
if "zip_decoder" in codecs:
tar = TarIO.TarIO(tarfile, 'lena.png')
im = Image.open(tar)
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "PNG")
if "jpeg_decoder" in codecs: class TestFileTar(PillowTestCase):
tar = TarIO.TarIO(tarfile, 'lena.jpg')
im = Image.open(tar)
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "JPEG")
def setUp(self):
if "zip_decoder" not in codecs and "jpeg_decoder" not in codecs:
self.skipTest("neither jpeg nor zip support not available")
def test_sanity(self):
if "zip_decoder" in codecs:
tar = TarIO.TarIO(tarfile, 'lena.png')
im = Image.open(tar)
im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "PNG")
if "jpeg_decoder" in codecs:
tar = TarIO.TarIO(tarfile, 'lena.jpg')
im = Image.open(tar)
im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "JPEG")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,141 +1,148 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena, py3
from PIL import Image from PIL import Image
def test_sanity():
file = tempfile("temp.tif") class TestFileTiff(PillowTestCase):
lena("RGB").save(file) def test_sanity(self):
im = Image.open(file) file = self.tempfile("temp.tif")
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "TIFF")
lena("1").save(file) lena("RGB").save(file)
im = Image.open(file)
lena("L").save(file) im = Image.open(file)
im = Image.open(file) im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "TIFF")
lena("P").save(file) lena("1").save(file)
im = Image.open(file) im = Image.open(file)
lena("RGB").save(file) lena("L").save(file)
im = Image.open(file) im = Image.open(file)
lena("I").save(file) lena("P").save(file)
im = Image.open(file) im = Image.open(file)
def test_mac_tiff(): lena("RGB").save(file)
# Read RGBa images from Mac OS X [@PIL136] im = Image.open(file)
file = "Tests/images/pil136.tiff" lena("I").save(file)
im = Image.open(file) im = Image.open(file)
assert_equal(im.mode, "RGBA") def test_mac_tiff(self):
assert_equal(im.size, (55, 43)) # Read RGBa images from Mac OS X [@PIL136]
assert_equal(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])
assert_no_exception(lambda: im.load())
def test_gimp_tiff(): file = "Tests/images/pil136.tiff"
# Read TIFF JPEG images from GIMP [@PIL168] im = Image.open(file)
codecs = dir(Image.core) self.assertEqual(im.mode, "RGBA")
if "jpeg_decoder" not in codecs: self.assertEqual(im.size, (55, 43))
skip("jpeg support not available") self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])
im.load()
file = "Tests/images/pil168.tif" def test_gimp_tiff(self):
im = Image.open(file) # Read TIFF JPEG images from GIMP [@PIL168]
assert_equal(im.mode, "RGB") codecs = dir(Image.core)
assert_equal(im.size, (256, 256)) if "jpeg_decoder" not in codecs:
assert_equal(im.tile, [ self.skipTest("jpeg support not available")
('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),
('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),
('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),
('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),
])
assert_no_exception(lambda: im.load())
def test_xyres_tiff(): file = "Tests/images/pil168.tif"
from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION im = Image.open(file)
file = "Tests/images/pil168.tif"
im = Image.open(file) self.assertEqual(im.mode, "RGB")
assert isinstance(im.tag.tags[X_RESOLUTION][0], tuple) self.assertEqual(im.size, (256, 256))
assert isinstance(im.tag.tags[Y_RESOLUTION][0], tuple) self.assertEqual(
#Try to read a file where X,Y_RESOLUTION are ints im.tile, [
im.tag.tags[X_RESOLUTION] = (72,) ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),
im.tag.tags[Y_RESOLUTION] = (72,) ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),
im._setup() ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),
assert_equal(im.info['dpi'], (72., 72.)) ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),
])
im.load()
def test_xyres_tiff(self):
from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION
file = "Tests/images/pil168.tif"
im = Image.open(file)
assert isinstance(im.tag.tags[X_RESOLUTION][0], tuple)
assert isinstance(im.tag.tags[Y_RESOLUTION][0], tuple)
# Try to read a file where X,Y_RESOLUTION are ints
im.tag.tags[X_RESOLUTION] = (72,)
im.tag.tags[Y_RESOLUTION] = (72,)
im._setup()
self.assertEqual(im.info['dpi'], (72., 72.))
def test_little_endian(self):
im = Image.open('Tests/images/16bit.cropped.tif')
self.assertEqual(im.getpixel((0, 0)), 480)
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'))
else:
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')
self.assertEqual(im.getpixel((0, 0)), 480)
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'))
else:
self.assertEqual(b[0], b'\x01')
self.assertEqual(b[1], b'\xe0')
def test_12bit_rawmode(self):
""" Are we generating the same interpretation
of the image as Imagemagick is? """
# Image.DEBUG = True
im = Image.open('Tests/images/12bit.cropped.tif')
# to make the target --
# convert 12bit.cropped.tif -depth 16 tmp.tif
# convert tmp.tif -evaluate RightShift 4 12in16bit2.tif
# 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.
im2 = Image.open('Tests/images/12in16bit.tif')
if Image.DEBUG:
print (im.getpixel((0, 0)))
print (im.getpixel((0, 1)))
print (im.getpixel((0, 2)))
print (im2.getpixel((0, 0)))
print (im2.getpixel((0, 1)))
print (im2.getpixel((0, 2)))
self.assert_image_equal(im, im2)
def test_32bit_float(self):
# Issue 614, specific 32 bit float format
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))
def test_little_endian(): if __name__ == '__main__':
im = Image.open('Tests/images/16bit.cropped.tif') unittest.main()
assert_equal(im.getpixel((0,0)), 480)
assert_equal(im.mode, 'I;16')
b = im.tobytes() # End of file
# Bytes are in image native order (little endian)
if py3:
assert_equal(b[0], ord(b'\xe0'))
assert_equal(b[1], ord(b'\x01'))
else:
assert_equal(b[0], b'\xe0')
assert_equal(b[1], b'\x01')
def test_big_endian():
im = Image.open('Tests/images/16bit.MM.cropped.tif')
assert_equal(im.getpixel((0,0)), 480)
assert_equal(im.mode, 'I;16B')
b = im.tobytes()
# Bytes are in image native order (big endian)
if py3:
assert_equal(b[0], ord(b'\x01'))
assert_equal(b[1], ord(b'\xe0'))
else:
assert_equal(b[0], b'\x01')
assert_equal(b[1], b'\xe0')
def test_12bit_rawmode():
""" Are we generating the same interpretation of the image as Imagemagick is? """
#Image.DEBUG = True
im = Image.open('Tests/images/12bit.cropped.tif')
# to make the target --
# convert 12bit.cropped.tif -depth 16 tmp.tif
# convert tmp.tif -evaluate RightShift 4 12in16bit2.tif
# 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.
im2 = Image.open('Tests/images/12in16bit.tif')
if Image.DEBUG:
print (im.getpixel((0,0)))
print (im.getpixel((0,1)))
print (im.getpixel((0,2)))
print (im2.getpixel((0,0)))
print (im2.getpixel((0,1)))
print (im2.getpixel((0,2)))
assert_image_equal(im, im2)
def test_32bit_float():
# Issue 614, specific 32 bit float format
path = 'Tests/images/10ct_32bit_128.tiff'
im = Image.open(path)
im.load()
assert_equal(im.getpixel((0,0)), -0.4526388943195343)
assert_equal(im.getextrema(), (-3.140936851501465, 3.140684127807617))

View File

@ -1,80 +1,93 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image, TiffImagePlugin, TiffTags from PIL import Image, TiffImagePlugin, TiffTags
tag_ids = dict(zip(TiffTags.TAGS.values(), TiffTags.TAGS.keys())) tag_ids = dict(zip(TiffTags.TAGS.values(), TiffTags.TAGS.keys()))
def test_rt_metadata():
""" Test writing arbitray metadata into the tiff image directory
Use case is ImageJ private tags, one numeric, one arbitrary
data. https://github.com/python-pillow/Pillow/issues/291
"""
img = lena() class TestFileTiffMetadata(PillowTestCase):
textdata = "This is some arbitrary metadata for a text field" def test_rt_metadata(self):
info = TiffImagePlugin.ImageFileDirectory() """ Test writing arbitray metadata into the tiff image directory
Use case is ImageJ private tags, one numeric, one arbitrary
data. https://github.com/python-pillow/Pillow/issues/291
"""
info[tag_ids['ImageJMetaDataByteCounts']] = len(textdata) img = lena()
info[tag_ids['ImageJMetaData']] = textdata
f = tempfile("temp.tif") textdata = "This is some arbitrary metadata for a text field"
info = TiffImagePlugin.ImageFileDirectory()
img.save(f, tiffinfo=info) info[tag_ids['ImageJMetaDataByteCounts']] = len(textdata)
info[tag_ids['ImageJMetaData']] = textdata
loaded = Image.open(f) f = self.tempfile("temp.tif")
assert_equal(loaded.tag[50838], (len(textdata),)) img.save(f, tiffinfo=info)
assert_equal(loaded.tag[50839], textdata)
def test_read_metadata(): loaded = Image.open(f)
img = Image.open('Tests/images/lena_g4.tif')
known = {'YResolution': ((1207959552, 16777216),), self.assertEqual(loaded.tag[50838], (len(textdata),))
'PlanarConfiguration': (1,), self.assertEqual(loaded.tag[50839], textdata)
'BitsPerSample': (1,),
'ImageLength': (128,),
'Compression': (4,),
'FillOrder': (1,),
'DocumentName': 'lena.g4.tif',
'RowsPerStrip': (128,),
'ResolutionUnit': (1,),
'PhotometricInterpretation': (0,),
'PageNumber': (0, 1),
'XResolution': ((1207959552, 16777216),),
'ImageWidth': (128,),
'Orientation': (1,),
'StripByteCounts': (1796,),
'SamplesPerPixel': (1,),
'StripOffsets': (8,),
'Software': 'ImageMagick 6.5.7-8 2012-08-17 Q16 http://www.imagemagick.org'}
# assert_equal is equivalent, but less helpful in telling what's wrong. def test_read_metadata(self):
named = img.tag.named() img = Image.open('Tests/images/lena_g4.tif')
for tag, value in named.items():
assert_equal(known[tag], value)
for tag, value in known.items(): known = {'YResolution': ((1207959552, 16777216),),
assert_equal(value, named[tag]) 'PlanarConfiguration': (1,),
'BitsPerSample': (1,),
'ImageLength': (128,),
'Compression': (4,),
'FillOrder': (1,),
'DocumentName': 'lena.g4.tif',
'RowsPerStrip': (128,),
'ResolutionUnit': (1,),
'PhotometricInterpretation': (0,),
'PageNumber': (0, 1),
'XResolution': ((1207959552, 16777216),),
'ImageWidth': (128,),
'Orientation': (1,),
'StripByteCounts': (1796,),
'SamplesPerPixel': (1,),
'StripOffsets': (8,),
'Software': 'ImageMagick 6.5.7-8 2012-08-17 Q16 http://www.imagemagick.org'}
# self.assertEqual is equivalent,
# but less helpful in telling what's wrong.
named = img.tag.named()
for tag, value in named.items():
self.assertEqual(known[tag], value)
for tag, value in known.items():
self.assertEqual(value, named[tag])
def test_write_metadata(self):
""" Test metadata writing through the python code """
img = Image.open('Tests/images/lena.tif')
f = self.tempfile('temp.tiff')
img.save(f, tiffinfo=img.tag)
loaded = Image.open(f)
original = img.tag.named()
reloaded = loaded.tag.named()
ignored = [
'StripByteCounts', 'RowsPerStrip', 'PageNumber', 'StripOffsets']
for tag, value in reloaded.items():
if tag not in ignored:
self.assertEqual(
original[tag], value, "%s didn't roundtrip" % tag)
for tag, value in original.items():
if tag not in ignored:
self.assertEqual(
value, reloaded[tag], "%s didn't roundtrip" % tag)
def test_write_metadata(): if __name__ == '__main__':
""" Test metadata writing through the python code """ unittest.main()
img = Image.open('Tests/images/lena.tif')
f = tempfile('temp.tiff') # End of file
img.save(f, tiffinfo = img.tag)
loaded = Image.open(f)
original = img.tag.named()
reloaded = loaded.tag.named()
ignored = ['StripByteCounts', 'RowsPerStrip', 'PageNumber', 'StripOffsets']
for tag, value in reloaded.items():
if tag not in ignored:
assert_equal(original[tag], value, "%s didn't roundtrip" % tag)
for tag, value in original.items():
if tag not in ignored:
assert_equal(value, reloaded[tag], "%s didn't roundtrip" % tag)

View File

@ -1,68 +1,79 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
try: try:
from PIL import _webp from PIL import _webp
except: except:
skip('webp support not installed') # Skip in setUp()
pass
def test_version(): class TestFileWebp(PillowTestCase):
assert_no_exception(lambda: _webp.WebPDecoderVersion())
assert_no_exception(lambda: _webp.WebPDecoderBuggyAlpha())
def test_read_rgb(): def setUp(self):
try:
from PIL import _webp
except:
self.skipTest('WebP support not installed')
file_path = "Images/lena.webp" def test_version(self):
image = Image.open(file_path) _webp.WebPDecoderVersion()
_webp.WebPDecoderBuggyAlpha()
assert_equal(image.mode, "RGB") def test_read_rgb(self):
assert_equal(image.size, (128, 128))
assert_equal(image.format, "WEBP")
assert_no_exception(lambda: image.load())
assert_no_exception(lambda: image.getdata())
# generated with: dwebp -ppm ../../Images/lena.webp -o lena_webp_bits.ppm
target = Image.open('Tests/images/lena_webp_bits.ppm')
assert_image_similar(image, target, 20.0)
def test_write_rgb():
"""
Can we write a RGB mode file to webp without error. Does it have the bits we
expect?
"""
temp_file = tempfile("temp.webp")
lena("RGB").save(temp_file)
image = Image.open(temp_file)
image.load()
assert_equal(image.mode, "RGB")
assert_equal(image.size, (128, 128))
assert_equal(image.format, "WEBP")
assert_no_exception(lambda: image.load())
assert_no_exception(lambda: image.getdata())
# If we're using the exact same version of webp, this test should pass.
# but it doesn't if the webp is generated on Ubuntu and tested on Fedora.
# generated with: dwebp -ppm temp.webp -o lena_webp_write.ppm
#target = Image.open('Tests/images/lena_webp_write.ppm')
#assert_image_equal(image, target)
# This test asserts that the images are similar. If the average pixel difference
# between the two images is less than the epsilon value, then we're going to
# accept that it's a reasonable lossy version of the image. The included lena images
# for webp are showing ~16 on Ubuntu, the jpegs are showing ~18.
target = lena("RGB")
assert_image_similar(image, target, 20.0)
file_path = "Images/lena.webp"
image = Image.open(file_path)
self.assertEqual(image.mode, "RGB")
self.assertEqual(image.size, (128, 128))
self.assertEqual(image.format, "WEBP")
image.load()
image.getdata()
# generated with:
# dwebp -ppm ../../Images/lena.webp -o lena_webp_bits.ppm
target = Image.open('Tests/images/lena_webp_bits.ppm')
self.assert_image_similar(image, target, 20.0)
def test_write_rgb(self):
"""
Can we write a RGB mode file to webp without error.
Does it have the bits we expect?
"""
temp_file = self.tempfile("temp.webp")
lena("RGB").save(temp_file)
image = Image.open(temp_file)
image.load()
self.assertEqual(image.mode, "RGB")
self.assertEqual(image.size, (128, 128))
self.assertEqual(image.format, "WEBP")
image.load()
image.getdata()
# If we're using the exact same version of WebP, this test should pass.
# but it doesn't if the WebP is generated on Ubuntu and tested on
# Fedora.
# generated with: dwebp -ppm temp.webp -o lena_webp_write.ppm
# target = Image.open('Tests/images/lena_webp_write.ppm')
# self.assert_image_equal(image, target)
# This test asserts that the images are similar. If the average pixel
# difference between the two images is less than the epsilon value,
# then we're going to accept that it's a reasonable lossy version of
# the image. The included lena images for WebP are showing ~16 on
# Ubuntu, the jpegs are showing ~18.
target = lena("RGB")
self.assert_image_similar(image, target, 20.0)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,82 +1,91 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
try: try:
from PIL import _webp from PIL import _webp
except: except:
skip('webp support not installed') pass
# Skip in setUp()
if _webp.WebPDecoderBuggyAlpha(): class TestFileWebpAlpha(PillowTestCase):
skip("Buggy early version of webp installed, not testing transparency")
def test_read_rgba(): def setUp(self):
# Generated with `cwebp transparent.png -o transparent.webp` try:
file_path = "Images/transparent.webp" from PIL import _webp
image = Image.open(file_path) except:
self.skipTest('WebP support not installed')
assert_equal(image.mode, "RGBA") if _webp.WebPDecoderBuggyAlpha(self):
assert_equal(image.size, (200, 150)) self.skipTest("Buggy early version of WebP installed, not testing transparency")
assert_equal(image.format, "WEBP")
assert_no_exception(lambda: image.load())
assert_no_exception(lambda: image.getdata())
orig_bytes = image.tobytes() def test_read_rgba(self):
# Generated with `cwebp transparent.png -o transparent.webp`
target = Image.open('Images/transparent.png') file_path = "Images/transparent.webp"
assert_image_similar(image, target, 20.0) image = Image.open(file_path)
def test_write_lossless_rgb():
temp_file = tempfile("temp.webp")
#temp_file = "temp.webp"
pil_image = lena('RGBA')
mask = Image.new("RGBA", (64, 64), (128,128,128,128))
pil_image.paste(mask, (0,0), mask) # add some partially transparent bits.
pil_image.save(temp_file, lossless=True)
image = Image.open(temp_file)
image.load()
assert_equal(image.mode, "RGBA")
assert_equal(image.size, pil_image.size)
assert_equal(image.format, "WEBP")
assert_no_exception(lambda: image.load())
assert_no_exception(lambda: image.getdata())
assert_image_equal(image, pil_image)
def test_write_rgba():
"""
Can we write a RGBA mode file to webp without error. Does it have the bits we
expect?
"""
temp_file = tempfile("temp.webp")
pil_image = Image.new("RGBA", (10, 10), (255, 0, 0, 20))
pil_image.save(temp_file)
if _webp.WebPDecoderBuggyAlpha():
return
image = Image.open(temp_file)
image.load()
assert_equal(image.mode, "RGBA")
assert_equal(image.size, (10, 10))
assert_equal(image.format, "WEBP")
assert_no_exception(image.load)
assert_no_exception(image.getdata)
assert_image_similar(image, pil_image, 1.0)
self.assertEqual(image.mode, "RGBA")
self.assertEqual(image.size, (200, 150))
self.assertEqual(image.format, "WEBP")
image.load()
image.getdata()
image.tobytes()
target = Image.open('Images/transparent.png')
self.assert_image_similar(image, target, 20.0)
def test_write_lossless_rgb(self):
temp_file = self.tempfile("temp.webp")
# temp_file = "temp.webp"
pil_image = lena('RGBA')
mask = Image.new("RGBA", (64, 64), (128, 128, 128, 128))
# Add some partially transparent bits:
pil_image.paste(mask, (0, 0), mask)
pil_image.save(temp_file, lossless=True)
image = Image.open(temp_file)
image.load()
self.assertEqual(image.mode, "RGBA")
self.assertEqual(image.size, pil_image.size)
self.assertEqual(image.format, "WEBP")
image.load()
image.getdata()
self.assert_image_equal(image, pil_image)
def test_write_rgba(self):
"""
Can we write a RGBA mode file to webp without error.
Does it have the bits we expect?
"""
temp_file = self.tempfile("temp.webp")
pil_image = Image.new("RGBA", (10, 10), (255, 0, 0, 20))
pil_image.save(temp_file)
if _webp.WebPDecoderBuggyAlpha(self):
return
image = Image.open(temp_file)
image.load()
self.assertEqual(image.mode, "RGBA")
self.assertEqual(image.size, (10, 10))
self.assertEqual(image.format, "WEBP")
image.load
image.getdata
self.assert_image_similar(image, pil_image, 1.0)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,33 +1,43 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
try: try:
from PIL import _webp from PIL import _webp
except: except:
skip('webp support not installed') pass
# Skip in setUp()
if (_webp.WebPDecoderVersion() < 0x0200): class TestFileWebpLossless(PillowTestCase):
skip('lossless not included')
def test_write_lossless_rgb(): def setUp(self):
temp_file = tempfile("temp.webp") try:
from PIL import _webp
except:
self.skipTest('WebP support not installed')
lena("RGB").save(temp_file, lossless=True) if (_webp.WebPDecoderVersion() < 0x0200):
self.skipTest('lossless not included')
image = Image.open(temp_file) def test_write_lossless_rgb(self):
image.load() temp_file = self.tempfile("temp.webp")
assert_equal(image.mode, "RGB") lena("RGB").save(temp_file, lossless=True)
assert_equal(image.size, (128, 128))
assert_equal(image.format, "WEBP") image = Image.open(temp_file)
assert_no_exception(lambda: image.load()) image.load()
assert_no_exception(lambda: image.getdata())
self.assertEqual(image.mode, "RGB")
self.assertEqual(image.size, (128, 128))
assert_image_equal(image, lena("RGB")) self.assertEqual(image.format, "WEBP")
image.load()
image.getdata()
self.assert_image_equal(image, lena("RGB"))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,101 +1,112 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
try:
from PIL import _webp class TestFileWebpMetadata(PillowTestCase):
if not _webp.HAVE_WEBPMUX:
skip('webpmux support not installed') def setUp(self):
except: try:
skip('webp support not installed') from PIL import _webp
if not _webp.HAVE_WEBPMUX:
self.skipTest('webpmux support not installed')
except:
self.skipTest('WebP support not installed')
def test_read_exif_metadata(self):
file_path = "Images/flower.webp"
image = Image.open(file_path)
self.assertEqual(image.format, "WEBP")
exif_data = image.info.get("exif", None)
self.assertTrue(exif_data)
exif = image._getexif()
# camera make
self.assertEqual(exif[271], "Canon")
jpeg_image = Image.open('Tests/images/flower.jpg')
expected_exif = jpeg_image.info['exif']
self.assertEqual(exif_data, expected_exif)
def test_write_exif_metadata(self):
from io import BytesIO
file_path = "Tests/images/flower.jpg"
image = Image.open(file_path)
expected_exif = image.info['exif']
buffer = BytesIO()
image.save(buffer, "webp", exif=expected_exif)
buffer.seek(0)
webp_image = Image.open(buffer)
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")
def test_read_icc_profile(self):
file_path = "Images/flower2.webp"
image = Image.open(file_path)
self.assertEqual(image.format, "WEBP")
self.assertTrue(image.info.get("icc_profile", None))
icc = image.info['icc_profile']
jpeg_image = Image.open('Tests/images/flower2.jpg')
expected_icc = jpeg_image.info['icc_profile']
self.assertEqual(icc, expected_icc)
def test_write_icc_metadata(self):
from io import BytesIO
file_path = "Tests/images/flower2.jpg"
image = Image.open(file_path)
expected_icc_profile = image.info['icc_profile']
buffer = BytesIO()
image.save(buffer, "webp", icc_profile=expected_icc_profile)
buffer.seek(0)
webp_image = Image.open(buffer)
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")
def test_read_no_exif(self):
from io import BytesIO
file_path = "Tests/images/flower.jpg"
image = Image.open(file_path)
image.info['exif']
buffer = BytesIO()
image.save(buffer, "webp")
buffer.seek(0)
webp_image = Image.open(buffer)
self.assertFalse(webp_image._getexif())
if __name__ == '__main__':
unittest.main()
def test_read_exif_metadata(): # End of file
file_path = "Images/flower.webp"
image = Image.open(file_path)
assert_equal(image.format, "WEBP")
exif_data = image.info.get("exif", None)
assert_true(exif_data)
exif = image._getexif()
#camera make
assert_equal(exif[271], "Canon")
jpeg_image = Image.open('Tests/images/flower.jpg')
expected_exif = jpeg_image.info['exif']
assert_equal(exif_data, expected_exif)
def test_write_exif_metadata():
file_path = "Tests/images/flower.jpg"
image = Image.open(file_path)
expected_exif = image.info['exif']
buffer = BytesIO()
image.save(buffer, "webp", exif=expected_exif)
buffer.seek(0)
webp_image = Image.open(buffer)
webp_exif = webp_image.info.get('exif', None)
assert_true(webp_exif)
if webp_exif:
assert_equal(webp_exif, expected_exif, "Webp Exif didn't match")
def test_read_icc_profile():
file_path = "Images/flower2.webp"
image = Image.open(file_path)
assert_equal(image.format, "WEBP")
assert_true(image.info.get("icc_profile", None))
icc = image.info['icc_profile']
jpeg_image = Image.open('Tests/images/flower2.jpg')
expected_icc = jpeg_image.info['icc_profile']
assert_equal(icc, expected_icc)
def test_write_icc_metadata():
file_path = "Tests/images/flower2.jpg"
image = Image.open(file_path)
expected_icc_profile = image.info['icc_profile']
buffer = BytesIO()
image.save(buffer, "webp", icc_profile=expected_icc_profile)
buffer.seek(0)
webp_image = Image.open(buffer)
webp_icc_profile = webp_image.info.get('icc_profile', None)
assert_true(webp_icc_profile)
if webp_icc_profile:
assert_equal(webp_icc_profile, expected_icc_profile, "Webp ICC didn't match")
def test_read_no_exif():
file_path = "Tests/images/flower.jpg"
image = Image.open(file_path)
expected_exif = image.info['exif']
buffer = BytesIO()
image.save(buffer, "webp")
buffer.seek(0)
webp_image = Image.open(buffer)
assert_false(webp_image._getexif())

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
@ -25,10 +25,20 @@ static char basic_bits[] = {
}; };
""" """
def test_pil151():
im = Image.open(BytesIO(PIL151)) class TestFileXbm(PillowTestCase):
assert_no_exception(lambda: im.load()) def test_pil151(self):
assert_equal(im.mode, '1') from io import BytesIO
assert_equal(im.size, (32, 32))
im = Image.open(BytesIO(PIL151))
im.load()
self.assertEqual(im.mode, '1')
self.assertEqual(im.size, (32, 32))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
@ -6,9 +6,18 @@ from PIL import Image
file = "Images/lena.xpm" file = "Images/lena.xpm"
data = open(file, "rb").read() data = open(file, "rb").read()
def test_sanity():
im = Image.open(file) class TestFileXpm(PillowTestCase):
im.load()
assert_equal(im.mode, "P") def test_sanity(self):
assert_equal(im.size, (128, 128)) im = Image.open(file)
assert_equal(im.format, "XPM") im.load()
self.assertEqual(im.mode, "P")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "XPM")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,13 +1,22 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image, FontFile, BdfFontFile from PIL import FontFile, BdfFontFile
filename = "Images/courB08.bdf" filename = "Images/courB08.bdf"
def test_sanity():
file = open(filename, "rb") class TestFontBdf(PillowTestCase):
font = BdfFontFile.BdfFontFile(file)
assert_true(isinstance(font, FontFile.FontFile)) def test_sanity(self):
assert_equal(len([_f for _f in font.glyph if _f]), 190)
file = open(filename, "rb")
font = BdfFontFile.BdfFontFile(file)
self.assertIsInstance(font, FontFile.FontFile)
self.assertEqual(len([_f for _f in font.glyph if _f]), 190)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,49 +1,63 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image, FontFile, PcfFontFile from PIL import Image, FontFile, PcfFontFile
from PIL import ImageFont, ImageDraw from PIL import ImageFont, ImageDraw
codecs = dir(Image.core) codecs = dir(Image.core)
if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
skip("zlib support not available")
fontname = "Tests/fonts/helvO18.pcf" fontname = "Tests/fonts/helvO18.pcf"
tempname = tempfile("temp.pil", "temp.pbm")
message = "hello, world" message = "hello, world"
def test_sanity():
file = open(fontname, "rb") class TestFontPcf(PillowTestCase):
font = PcfFontFile.PcfFontFile(file)
assert_true(isinstance(font, FontFile.FontFile))
assert_equal(len([_f for _f in font.glyph if _f]), 192)
font.save(tempname) def setUp(self):
if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
self.skipTest("zlib support not available")
def xtest_draw(): def save_font(self):
file = open(fontname, "rb")
font = PcfFontFile.PcfFontFile(file)
self.assertIsInstance(font, FontFile.FontFile)
self.assertEqual(len([_f for _f in font.glyph if _f]), 192)
font = ImageFont.load(tempname) tempname = self.tempfile("temp.pil", "temp.pbm")
image = Image.new("L", font.getsize(message), "white") font.save(tempname)
draw = ImageDraw.Draw(image) return tempname
draw.text((0, 0), message, font=font)
# assert_signature(image, "7216c60f988dea43a46bb68321e3c1b03ec62aee")
def _test_high_characters(message): def test_sanity(self):
self.save_font()
font = ImageFont.load(tempname) def xtest_draw(self):
image = Image.new("L", font.getsize(message), "white")
draw = ImageDraw.Draw(image)
draw.text((0, 0), message, font=font)
compare = Image.open('Tests/images/high_ascii_chars.png') tempname = self.save_font()
assert_image_equal(image, compare) font = ImageFont.load(tempname)
image = Image.new("L", font.getsize(message), "white")
draw = ImageDraw.Draw(image)
draw.text((0, 0), message, font=font)
# assert_signature(image, "7216c60f988dea43a46bb68321e3c1b03ec62aee")
def test_high_characters(): def _test_high_characters(self, message):
message = "".join([chr(i+1) for i in range(140,232)])
_test_high_characters(message)
# accept bytes instances in Py3.
if bytes is not str:
_test_high_characters(message.encode('latin1'))
tempname = self.save_font()
font = ImageFont.load(tempname)
image = Image.new("L", font.getsize(message), "white")
draw = ImageDraw.Draw(image)
draw.text((0, 0), message, font=font)
compare = Image.open('Tests/images/high_ascii_chars.png')
self.assert_image_equal(image, compare)
def test_high_characters(self):
message = "".join([chr(i+1) for i in range(140, 232)])
self._test_high_characters(message)
# accept bytes instances in Py3.
if bytes is not str:
self._test_high_characters(message.encode('latin1'))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,41 +1,48 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
def test_white():
i = Image.open('Tests/images/lab.tif')
bits = i.load() class TestFormatLab(PillowTestCase):
assert_equal(i.mode, 'LAB')
assert_equal(i.getbands(), ('L','A', 'B')) def test_white(self):
i = Image.open('Tests/images/lab.tif')
k = i.getpixel((0,0)) i.load()
assert_equal(k, (255,128,128))
L = i.getdata(0) self.assertEqual(i.mode, 'LAB')
a = i.getdata(1)
b = i.getdata(2)
assert_equal(list(L), [255]*100) self.assertEqual(i.getbands(), ('L', 'A', 'B'))
assert_equal(list(a), [128]*100)
assert_equal(list(b), [128]*100)
def test_green(): k = i.getpixel((0, 0))
# l= 50 (/100), a = -100 (-128 .. 128) b=0 in PS self.assertEqual(k, (255, 128, 128))
# == RGB: 0, 152, 117
i = Image.open('Tests/images/lab-green.tif')
k = i.getpixel((0,0)) L = i.getdata(0)
assert_equal(k, (128,28,128)) a = i.getdata(1)
b = i.getdata(2)
self.assertEqual(list(L), [255]*100)
self.assertEqual(list(a), [128]*100)
self.assertEqual(list(b), [128]*100)
def test_green(self):
# l= 50 (/100), a = -100 (-128 .. 128) b=0 in PS
# == RGB: 0, 152, 117
i = Image.open('Tests/images/lab-green.tif')
k = i.getpixel((0, 0))
self.assertEqual(k, (128, 28, 128))
def test_red(self):
# l= 50 (/100), a = 100 (-128 .. 128) b=0 in PS
# == RGB: 255, 0, 124
i = Image.open('Tests/images/lab-red.tif')
k = i.getpixel((0, 0))
self.assertEqual(k, (128, 228, 128))
def test_red(): if __name__ == '__main__':
# l= 50 (/100), a = 100 (-128 .. 128) b=0 in PS unittest.main()
# == RGB: 255, 0, 124
i = Image.open('Tests/images/lab-red.tif')
k = i.getpixel((0,0)) # End of file
assert_equal(k, (128,228,128))

View File

@ -1,39 +1,51 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
def test_sanity():
im = Image.new("L", (100, 100)) class TestImage(PillowTestCase):
assert_equal(repr(im)[:45], "<PIL.Image.Image image mode=L size=100x100 at")
assert_equal(im.mode, "L")
assert_equal(im.size, (100, 100))
im = Image.new("RGB", (100, 100)) def test_sanity(self):
assert_equal(repr(im)[:45], "<PIL.Image.Image image mode=RGB size=100x100 ")
assert_equal(im.mode, "RGB")
assert_equal(im.size, (100, 100))
im1 = Image.new("L", (100, 100), None) im = Image.new("L", (100, 100))
im2 = Image.new("L", (100, 100), 0) self.assertEqual(
im3 = Image.new("L", (100, 100), "black") repr(im)[:45], "<PIL.Image.Image image mode=L size=100x100 at")
self.assertEqual(im.mode, "L")
self.assertEqual(im.size, (100, 100))
assert_equal(im2.getcolors(), [(10000, 0)]) im = Image.new("RGB", (100, 100))
assert_equal(im3.getcolors(), [(10000, 0)]) self.assertEqual(
repr(im)[:45], "<PIL.Image.Image image mode=RGB size=100x100 ")
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (100, 100))
assert_exception(ValueError, lambda: Image.new("X", (100, 100))) Image.new("L", (100, 100), None)
# assert_exception(MemoryError, lambda: Image.new("L", (1000000, 1000000))) im2 = Image.new("L", (100, 100), 0)
im3 = Image.new("L", (100, 100), "black")
def test_internals(): self.assertEqual(im2.getcolors(), [(10000, 0)])
self.assertEqual(im3.getcolors(), [(10000, 0)])
im = Image.new("L", (100, 100)) self.assertRaises(ValueError, lambda: Image.new("X", (100, 100)))
im.readonly = 1 # self.assertRaises(
im._copy() # MemoryError, lambda: Image.new("L", (1000000, 1000000)))
assert_false(im.readonly)
im.readonly = 1 def test_internals(self):
im.paste(0, (0, 0, 100, 100))
assert_false(im.readonly)
file = tempfile("temp.ppm") im = Image.new("L", (100, 100))
im._dump(file) im.readonly = 1
im._copy()
self.assertFalse(im.readonly)
im.readonly = 1
im.paste(0, (0, 0, 100, 100))
self.assertFalse(im.readonly)
file = self.tempfile("temp.ppm")
im._dump(file)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,33 +1,46 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
im = lena().resize((128, 100)) im = lena().resize((128, 100))
def test_toarray():
def test(mode):
ai = im.convert(mode).__array_interface__
return ai["shape"], ai["typestr"], len(ai["data"])
# assert_equal(test("1"), ((100, 128), '|b1', 1600))
assert_equal(test("L"), ((100, 128), '|u1', 12800))
assert_equal(test("I"), ((100, 128), Image._ENDIAN + 'i4', 51200)) # FIXME: wrong?
assert_equal(test("F"), ((100, 128), Image._ENDIAN + 'f4', 51200)) # FIXME: wrong?
assert_equal(test("RGB"), ((100, 128, 3), '|u1', 38400))
assert_equal(test("RGBA"), ((100, 128, 4), '|u1', 51200))
assert_equal(test("RGBX"), ((100, 128, 4), '|u1', 51200))
def test_fromarray(): class TestImageCrop(PillowTestCase):
def test(mode):
i = im.convert(mode) def test_toarray(self):
a = i.__array_interface__ def test(mode):
a["strides"] = 1 # pretend it's non-contigous ai = im.convert(mode).__array_interface__
i.__array_interface__ = a # patch in new version of attribute return ai["shape"], ai["typestr"], len(ai["data"])
out = Image.fromarray(i) # self.assertEqual(test("1"), ((100, 128), '|b1', 1600))
return out.mode, out.size, list(i.getdata()) == list(out.getdata()) self.assertEqual(test("L"), ((100, 128), '|u1', 12800))
# assert_equal(test("1"), ("1", (128, 100), True))
assert_equal(test("L"), ("L", (128, 100), True)) # FIXME: wrong?
assert_equal(test("I"), ("I", (128, 100), True)) self.assertEqual(test("I"), ((100, 128), Image._ENDIAN + 'i4', 51200))
assert_equal(test("F"), ("F", (128, 100), True)) # FIXME: wrong?
assert_equal(test("RGB"), ("RGB", (128, 100), True)) self.assertEqual(test("F"), ((100, 128), Image._ENDIAN + 'f4', 51200))
assert_equal(test("RGBA"), ("RGBA", (128, 100), True))
assert_equal(test("RGBX"), ("RGBA", (128, 100), True)) self.assertEqual(test("RGB"), ((100, 128, 3), '|u1', 38400))
self.assertEqual(test("RGBA"), ((100, 128, 4), '|u1', 51200))
self.assertEqual(test("RGBX"), ((100, 128, 4), '|u1', 51200))
def test_fromarray(self):
def test(mode):
i = im.convert(mode)
a = i.__array_interface__
a["strides"] = 1 # pretend it's non-contigous
i.__array_interface__ = a # patch in new version of attribute
out = Image.fromarray(i)
return out.mode, out.size, list(i.getdata()) == list(out.getdata())
# self.assertEqual(test("1"), ("1", (128, 100), True))
self.assertEqual(test("L"), ("L", (128, 100), True))
self.assertEqual(test("I"), ("I", (128, 100), True))
self.assertEqual(test("F"), ("F", (128, 100), True))
self.assertEqual(test("RGB"), ("RGB", (128, 100), True))
self.assertEqual(test("RGBA"), ("RGBA", (128, 100), True))
self.assertEqual(test("RGBX"), ("RGBA", (128, 100), True))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,130 +1,130 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_sanity(): class TestImageConvert(PillowTestCase):
def convert(im, mode): def test_sanity(self):
out = im.convert(mode)
assert_equal(out.mode, mode)
assert_equal(out.size, im.size)
modes = "1", "L", "I", "F", "RGB", "RGBA", "RGBX", "CMYK", "YCbCr" def convert(im, mode):
out = im.convert(mode)
self.assertEqual(out.mode, mode)
self.assertEqual(out.size, im.size)
modes = "1", "L", "I", "F", "RGB", "RGBA", "RGBX", "CMYK", "YCbCr"
for mode in modes:
im = lena(mode)
for mode in modes: for mode in modes:
yield_test(convert, im, mode) im = lena(mode)
for mode in modes:
convert(im, mode)
def test_default(self):
im = lena("P")
self.assert_image(im, "P", im.size)
im = im.convert()
self.assert_image(im, "RGB", im.size)
im = im.convert()
self.assert_image(im, "RGB", im.size)
# ref https://github.com/python-pillow/Pillow/issues/274
def _test_float_conversion(self, im):
orig = im.getpixel((5, 5))
converted = im.convert('F').getpixel((5, 5))
self.assertEqual(orig, converted)
def test_8bit(self):
im = Image.open('Images/lena.jpg')
self._test_float_conversion(im.convert('L'))
def test_16bit(self):
im = Image.open('Tests/images/16bit.cropped.tif')
self._test_float_conversion(im)
def test_16bit_workaround(self):
im = Image.open('Tests/images/16bit.cropped.tif')
self._test_float_conversion(im.convert('I'))
def test_rgba_p(self):
im = lena('RGBA')
im.putalpha(lena('L'))
converted = im.convert('P')
comparable = converted.convert('RGBA')
self.assert_image_similar(im, comparable, 20)
def test_trns_p(self):
im = lena('P')
im.info['transparency'] = 0
f = self.tempfile('temp.png')
l = im.convert('L')
self.assertEqual(l.info['transparency'], 0) # undone
l.save(f)
rgb = im.convert('RGB')
self.assertEqual(rgb.info['transparency'], (0, 0, 0)) # undone
rgb.save(f)
# ref https://github.com/python-pillow/Pillow/issues/664
def test_trns_p_rgba(self):
# Arrange
im = lena('P')
im.info['transparency'] = 128
# Act
rgba = im.convert('RGBA')
# Assert
self.assertNotIn('transparency', rgba.info)
def test_trns_l(self):
im = lena('L')
im.info['transparency'] = 128
f = self.tempfile('temp.png')
rgb = im.convert('RGB')
self.assertEqual(rgb.info['transparency'], (128, 128, 128)) # undone
rgb.save(f)
p = im.convert('P')
self.assertIn('transparency', p.info)
p.save(f)
p = self.assert_warning(
UserWarning,
lambda: im.convert('P', palette=Image.ADAPTIVE))
self.assertNotIn('transparency', p.info)
p.save(f)
def test_trns_RGB(self):
im = lena('RGB')
im.info['transparency'] = im.getpixel((0, 0))
f = self.tempfile('temp.png')
l = im.convert('L')
self.assertEqual(l.info['transparency'], l.getpixel((0, 0))) # undone
l.save(f)
p = im.convert('P')
self.assertIn('transparency', p.info)
p.save(f)
p = self.assert_warning(
UserWarning,
lambda: im.convert('P', palette=Image.ADAPTIVE))
self.assertNotIn('transparency', p.info)
p.save(f)
def test_default(): if __name__ == '__main__':
unittest.main()
im = lena("P") # End of file
assert_image(im, "P", im.size)
im = im.convert()
assert_image(im, "RGB", im.size)
im = im.convert()
assert_image(im, "RGB", im.size)
# ref https://github.com/python-pillow/Pillow/issues/274
def _test_float_conversion(im):
orig = im.getpixel((5, 5))
converted = im.convert('F').getpixel((5, 5))
assert_equal(orig, converted)
def test_8bit():
im = Image.open('Images/lena.jpg')
_test_float_conversion(im.convert('L'))
def test_16bit():
im = Image.open('Tests/images/16bit.cropped.tif')
_test_float_conversion(im)
def test_16bit_workaround():
im = Image.open('Tests/images/16bit.cropped.tif')
_test_float_conversion(im.convert('I'))
def test_rgba_p():
im = lena('RGBA')
im.putalpha(lena('L'))
converted = im.convert('P')
comparable = converted.convert('RGBA')
assert_image_similar(im, comparable, 20)
def test_trns_p():
im = lena('P')
im.info['transparency'] = 0
f = tempfile('temp.png')
l = im.convert('L')
assert_equal(l.info['transparency'], 0) # undone
assert_no_exception(lambda: l.save(f))
rgb = im.convert('RGB')
assert_equal(rgb.info['transparency'], (0, 0, 0)) # undone
assert_no_exception(lambda: rgb.save(f))
# ref https://github.com/python-pillow/Pillow/issues/664
def test_trns_p_rgba():
# Arrange
im = lena('P')
im.info['transparency'] = 128
# Act
rgba = im.convert('RGBA')
# Assert
assert_false('transparency' in rgba.info)
def test_trns_l():
im = lena('L')
im.info['transparency'] = 128
f = tempfile('temp.png')
rgb = im.convert('RGB')
assert_equal(rgb.info['transparency'], (128, 128, 128)) # undone
assert_no_exception(lambda: rgb.save(f))
p = im.convert('P')
assert_true('transparency' in p.info)
assert_no_exception(lambda: p.save(f))
p = assert_warning(UserWarning,
lambda: im.convert('P', palette=Image.ADAPTIVE))
assert_false('transparency' in p.info)
assert_no_exception(lambda: p.save(f))
def test_trns_RGB():
im = lena('RGB')
im.info['transparency'] = im.getpixel((0, 0))
f = tempfile('temp.png')
l = im.convert('L')
assert_equal(l.info['transparency'], l.getpixel((0, 0))) # undone
assert_no_exception(lambda: l.save(f))
p = im.convert('P')
assert_true('transparency' in p.info)
assert_no_exception(lambda: p.save(f))
p = assert_warning(UserWarning,
lambda: im.convert('P', palette=Image.ADAPTIVE))
assert_false('transparency' in p.info)
assert_no_exception(lambda: p.save(f))

View File

@ -1,12 +1,20 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_copy():
def copy(mode): class TestImageCopy(PillowTestCase):
im = lena(mode)
out = im.copy() def test_copy(self):
assert_equal(out.mode, mode) def copy(mode):
assert_equal(out.size, im.size) im = lena(mode)
for mode in "1", "P", "L", "RGB", "I", "F": out = im.copy()
yield_test(copy, mode) self.assertEqual(out.mode, mode)
self.assertEqual(out.size, im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
copy(mode)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,52 +1,59 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_crop():
def crop(mode):
out = lena(mode).crop((50, 50, 100, 100))
assert_equal(out.mode, mode)
assert_equal(out.size, (50, 50))
for mode in "1", "P", "L", "RGB", "I", "F":
yield_test(crop, mode)
def test_wide_crop(): class TestImageCrop(PillowTestCase):
def crop(*bbox): def test_crop(self):
i = im.crop(bbox) def crop(mode):
h = i.histogram() out = lena(mode).crop((50, 50, 100, 100))
while h and not h[-1]: self.assertEqual(out.mode, mode)
del h[-1] self.assertEqual(out.size, (50, 50))
return tuple(h) for mode in "1", "P", "L", "RGB", "I", "F":
crop(mode)
im = Image.new("L", (100, 100), 1) def test_wide_crop(self):
assert_equal(crop(0, 0, 100, 100), (0, 10000)) def crop(*bbox):
assert_equal(crop(25, 25, 75, 75), (0, 2500)) i = im.crop(bbox)
h = i.histogram()
while h and not h[-1]:
del h[-1]
return tuple(h)
# sides im = Image.new("L", (100, 100), 1)
assert_equal(crop(-25, 0, 25, 50), (1250, 1250))
assert_equal(crop(0, -25, 50, 25), (1250, 1250))
assert_equal(crop(75, 0, 125, 50), (1250, 1250))
assert_equal(crop(0, 75, 50, 125), (1250, 1250))
assert_equal(crop(-25, 25, 125, 75), (2500, 5000)) self.assertEqual(crop(0, 0, 100, 100), (0, 10000))
assert_equal(crop(25, -25, 75, 125), (2500, 5000)) self.assertEqual(crop(25, 25, 75, 75), (0, 2500))
# corners # sides
assert_equal(crop(-25, -25, 25, 25), (1875, 625)) self.assertEqual(crop(-25, 0, 25, 50), (1250, 1250))
assert_equal(crop(75, -25, 125, 25), (1875, 625)) self.assertEqual(crop(0, -25, 50, 25), (1250, 1250))
assert_equal(crop(75, 75, 125, 125), (1875, 625)) self.assertEqual(crop(75, 0, 125, 50), (1250, 1250))
assert_equal(crop(-25, 75, 25, 125), (1875, 625)) self.assertEqual(crop(0, 75, 50, 125), (1250, 1250))
# -------------------------------------------------------------------- self.assertEqual(crop(-25, 25, 125, 75), (2500, 5000))
self.assertEqual(crop(25, -25, 75, 125), (2500, 5000))
def test_negative_crop(): # corners
# Check negative crop size (@PIL171) self.assertEqual(crop(-25, -25, 25, 25), (1875, 625))
self.assertEqual(crop(75, -25, 125, 25), (1875, 625))
self.assertEqual(crop(75, 75, 125, 125), (1875, 625))
self.assertEqual(crop(-25, 75, 25, 125), (1875, 625))
im = Image.new("L", (512, 512)) def test_negative_crop(self):
im = im.crop((400, 400, 200, 200)) # Check negative crop size (@PIL171)
assert_equal(im.size, (0, 0)) im = Image.new("L", (512, 512))
assert_equal(len(im.getdata()), 0) im = im.crop((400, 400, 200, 200))
assert_exception(IndexError, lambda: im.getdata()[0])
self.assertEqual(im.size, (0, 0))
self.assertEqual(len(im.getdata()), 0)
self.assertRaises(IndexError, lambda: im.getdata()[0])
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,30 +1,39 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, fromstring, tostring
from PIL import Image from PIL import Image
codecs = dir(Image.core) codecs = dir(Image.core)
if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:
skip("jpeg support not available")
filename = "Images/lena.jpg" filename = "Images/lena.jpg"
data = tostring(Image.open(filename).resize((512, 512)), "JPEG") data = tostring(Image.open(filename).resize((512, 512)), "JPEG")
def draft(mode, size): def draft(mode, size):
im = fromstring(data) im = fromstring(data)
im.draft(mode, size) im.draft(mode, size)
return im return im
def test_size():
assert_equal(draft("RGB", (512, 512)).size, (512, 512))
assert_equal(draft("RGB", (256, 256)).size, (256, 256))
assert_equal(draft("RGB", (128, 128)).size, (128, 128))
assert_equal(draft("RGB", (64, 64)).size, (64, 64))
assert_equal(draft("RGB", (32, 32)).size, (64, 64))
def test_mode(): class TestImageDraft(PillowTestCase):
assert_equal(draft("1", (512, 512)).mode, "RGB")
assert_equal(draft("L", (512, 512)).mode, "L") def setUp(self):
assert_equal(draft("RGB", (512, 512)).mode, "RGB") if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs:
assert_equal(draft("YCbCr", (512, 512)).mode, "YCbCr") self.skipTest("jpeg support not available")
def test_size(self):
self.assertEqual(draft("RGB", (512, 512)).size, (512, 512))
self.assertEqual(draft("RGB", (256, 256)).size, (256, 256))
self.assertEqual(draft("RGB", (128, 128)).size, (128, 128))
self.assertEqual(draft("RGB", (64, 64)).size, (64, 64))
self.assertEqual(draft("RGB", (32, 32)).size, (64, 64))
def test_mode(self):
self.assertEqual(draft("1", (512, 512)).mode, "RGB")
self.assertEqual(draft("L", (512, 512)).mode, "L")
self.assertEqual(draft("RGB", (512, 512)).mode, "RGB")
self.assertEqual(draft("YCbCr", (512, 512)).mode, "YCbCr")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,82 +1,91 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
from PIL import ImageFilter from PIL import ImageFilter
def test_sanity():
def filter(filter): class TestImageFilter(PillowTestCase):
im = lena("L")
out = im.filter(filter)
assert_equal(out.mode, im.mode)
assert_equal(out.size, im.size)
filter(ImageFilter.BLUR) def test_sanity(self):
filter(ImageFilter.CONTOUR)
filter(ImageFilter.DETAIL)
filter(ImageFilter.EDGE_ENHANCE)
filter(ImageFilter.EDGE_ENHANCE_MORE)
filter(ImageFilter.EMBOSS)
filter(ImageFilter.FIND_EDGES)
filter(ImageFilter.SMOOTH)
filter(ImageFilter.SMOOTH_MORE)
filter(ImageFilter.SHARPEN)
filter(ImageFilter.MaxFilter)
filter(ImageFilter.MedianFilter)
filter(ImageFilter.MinFilter)
filter(ImageFilter.ModeFilter)
filter(ImageFilter.Kernel((3, 3), list(range(9))))
assert_exception(TypeError, lambda: filter("hello")) def filter(filter):
im = lena("L")
out = im.filter(filter)
self.assertEqual(out.mode, im.mode)
self.assertEqual(out.size, im.size)
def test_crash(): filter(ImageFilter.BLUR)
filter(ImageFilter.CONTOUR)
filter(ImageFilter.DETAIL)
filter(ImageFilter.EDGE_ENHANCE)
filter(ImageFilter.EDGE_ENHANCE_MORE)
filter(ImageFilter.EMBOSS)
filter(ImageFilter.FIND_EDGES)
filter(ImageFilter.SMOOTH)
filter(ImageFilter.SMOOTH_MORE)
filter(ImageFilter.SHARPEN)
filter(ImageFilter.MaxFilter)
filter(ImageFilter.MedianFilter)
filter(ImageFilter.MinFilter)
filter(ImageFilter.ModeFilter)
filter(ImageFilter.Kernel((3, 3), list(range(9))))
# crashes on small images self.assertRaises(TypeError, lambda: filter("hello"))
im = Image.new("RGB", (1, 1))
assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH))
im = Image.new("RGB", (2, 2)) def test_crash(self):
assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH))
im = Image.new("RGB", (3, 3)) # crashes on small images
assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH)) im = Image.new("RGB", (1, 1))
im.filter(ImageFilter.SMOOTH)
def test_modefilter(): im = Image.new("RGB", (2, 2))
im.filter(ImageFilter.SMOOTH)
def modefilter(mode): im = Image.new("RGB", (3, 3))
im = Image.new(mode, (3, 3), None) im.filter(ImageFilter.SMOOTH)
im.putdata(list(range(9)))
# image is:
# 0 1 2
# 3 4 5
# 6 7 8
mod = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
im.putdata([0, 0, 1, 2, 5, 1, 5, 2, 0]) # mode=0
mod2 = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
return mod, mod2
assert_equal(modefilter("1"), (4, 0)) def test_modefilter(self):
assert_equal(modefilter("L"), (4, 0))
assert_equal(modefilter("P"), (4, 0))
assert_equal(modefilter("RGB"), ((4, 0, 0), (0, 0, 0)))
def test_rankfilter(): def modefilter(mode):
im = Image.new(mode, (3, 3), None)
im.putdata(list(range(9)))
# image is:
# 0 1 2
# 3 4 5
# 6 7 8
mod = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
im.putdata([0, 0, 1, 2, 5, 1, 5, 2, 0]) # mode=0
mod2 = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
return mod, mod2
def rankfilter(mode): self.assertEqual(modefilter("1"), (4, 0))
im = Image.new(mode, (3, 3), None) self.assertEqual(modefilter("L"), (4, 0))
im.putdata(list(range(9))) self.assertEqual(modefilter("P"), (4, 0))
# image is: self.assertEqual(modefilter("RGB"), ((4, 0, 0), (0, 0, 0)))
# 0 1 2
# 3 4 5
# 6 7 8
min = im.filter(ImageFilter.MinFilter).getpixel((1, 1))
med = im.filter(ImageFilter.MedianFilter).getpixel((1, 1))
max = im.filter(ImageFilter.MaxFilter).getpixel((1, 1))
return min, med, max
assert_equal(rankfilter("1"), (0, 4, 8)) def test_rankfilter(self):
assert_equal(rankfilter("L"), (0, 4, 8))
assert_exception(ValueError, lambda: rankfilter("P")) def rankfilter(mode):
assert_equal(rankfilter("RGB"), ((0, 0, 0), (4, 0, 0), (8, 0, 0))) im = Image.new(mode, (3, 3), None)
assert_equal(rankfilter("I"), (0, 4, 8)) im.putdata(list(range(9)))
assert_equal(rankfilter("F"), (0.0, 4.0, 8.0)) # image is:
# 0 1 2
# 3 4 5
# 6 7 8
min = im.filter(ImageFilter.MinFilter).getpixel((1, 1))
med = im.filter(ImageFilter.MedianFilter).getpixel((1, 1))
max = im.filter(ImageFilter.MaxFilter).getpixel((1, 1))
return min, med, max
self.assertEqual(rankfilter("1"), (0, 4, 8))
self.assertEqual(rankfilter("L"), (0, 4, 8))
self.assertRaises(ValueError, lambda: rankfilter("P"))
self.assertEqual(rankfilter("RGB"), ((0, 0, 0), (4, 0, 0), (8, 0, 0)))
self.assertEqual(rankfilter("I"), (0, 4, 8))
self.assertEqual(rankfilter("F"), (0.0, 4.0, 8.0))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,10 +1,18 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_sanity():
im1 = lena()
im2 = Image.frombytes(im1.mode, im1.size, im1.tobytes())
assert_image_equal(im1, im2) class TestImageFromBytes(PillowTestCase):
def test_sanity(self):
im1 = lena()
im2 = Image.frombytes(im1.mode, im1.size, im1.tobytes())
self.assert_image_equal(im1, im2)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,15 +1,26 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
def test_getbands():
assert_equal(Image.new("1", (1, 1)).getbands(), ("1",)) class TestImageGetBands(PillowTestCase):
assert_equal(Image.new("L", (1, 1)).getbands(), ("L",))
assert_equal(Image.new("I", (1, 1)).getbands(), ("I",)) def test_getbands(self):
assert_equal(Image.new("F", (1, 1)).getbands(), ("F",)) self.assertEqual(Image.new("1", (1, 1)).getbands(), ("1",))
assert_equal(Image.new("P", (1, 1)).getbands(), ("P",)) self.assertEqual(Image.new("L", (1, 1)).getbands(), ("L",))
assert_equal(Image.new("RGB", (1, 1)).getbands(), ("R", "G", "B")) self.assertEqual(Image.new("I", (1, 1)).getbands(), ("I",))
assert_equal(Image.new("RGBA", (1, 1)).getbands(), ("R", "G", "B", "A")) self.assertEqual(Image.new("F", (1, 1)).getbands(), ("F",))
assert_equal(Image.new("CMYK", (1, 1)).getbands(), ("C", "M", "Y", "K")) self.assertEqual(Image.new("P", (1, 1)).getbands(), ("P",))
assert_equal(Image.new("YCbCr", (1, 1)).getbands(), ("Y", "Cb", "Cr")) self.assertEqual(Image.new("RGB", (1, 1)).getbands(), ("R", "G", "B"))
self.assertEqual(
Image.new("RGBA", (1, 1)).getbands(), ("R", "G", "B", "A"))
self.assertEqual(
Image.new("CMYK", (1, 1)).getbands(), ("C", "M", "Y", "K"))
self.assertEqual(
Image.new("YCbCr", (1, 1)).getbands(), ("Y", "Cb", "Cr"))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,36 +1,45 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_sanity():
bbox = lena().getbbox() class TestImageGetBbox(PillowTestCase):
assert_true(isinstance(bbox, tuple))
def test_bbox(): def test_sanity(self):
# 8-bit mode bbox = lena().getbbox()
im = Image.new("L", (100, 100), 0) self.assertIsInstance(bbox, tuple)
assert_equal(im.getbbox(), None)
im.paste(255, (10, 25, 90, 75)) def test_bbox(self):
assert_equal(im.getbbox(), (10, 25, 90, 75))
im.paste(255, (25, 10, 75, 90)) # 8-bit mode
assert_equal(im.getbbox(), (10, 10, 90, 90)) im = Image.new("L", (100, 100), 0)
self.assertEqual(im.getbbox(), None)
im.paste(255, (-10, -10, 110, 110)) im.paste(255, (10, 25, 90, 75))
assert_equal(im.getbbox(), (0, 0, 100, 100)) self.assertEqual(im.getbbox(), (10, 25, 90, 75))
# 32-bit mode im.paste(255, (25, 10, 75, 90))
im = Image.new("RGB", (100, 100), 0) self.assertEqual(im.getbbox(), (10, 10, 90, 90))
assert_equal(im.getbbox(), None)
im.paste(255, (10, 25, 90, 75)) im.paste(255, (-10, -10, 110, 110))
assert_equal(im.getbbox(), (10, 25, 90, 75)) self.assertEqual(im.getbbox(), (0, 0, 100, 100))
im.paste(255, (25, 10, 75, 90)) # 32-bit mode
assert_equal(im.getbbox(), (10, 10, 90, 90)) im = Image.new("RGB", (100, 100), 0)
self.assertEqual(im.getbbox(), None)
im.paste(255, (-10, -10, 110, 110)) im.paste(255, (10, 25, 90, 75))
assert_equal(im.getbbox(), (0, 0, 100, 100)) self.assertEqual(im.getbbox(), (10, 25, 90, 75))
im.paste(255, (25, 10, 75, 90))
self.assertEqual(im.getbbox(), (10, 10, 90, 90))
im.paste(255, (-10, -10, 110, 110))
self.assertEqual(im.getbbox(), (0, 0, 100, 100))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,64 +1,74 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_getcolors(): class TestImageGetColors(PillowTestCase):
def getcolors(mode, limit=None): def test_getcolors(self):
im = lena(mode)
if limit:
colors = im.getcolors(limit)
else:
colors = im.getcolors()
if colors:
return len(colors)
return None
assert_equal(getcolors("1"), 2) def getcolors(mode, limit=None):
assert_equal(getcolors("L"), 193) im = lena(mode)
assert_equal(getcolors("I"), 193) if limit:
assert_equal(getcolors("F"), 193) colors = im.getcolors(limit)
assert_equal(getcolors("P"), 54) # fixed palette else:
assert_equal(getcolors("RGB"), None) colors = im.getcolors()
assert_equal(getcolors("RGBA"), None) if colors:
assert_equal(getcolors("CMYK"), None) return len(colors)
assert_equal(getcolors("YCbCr"), None) return None
assert_equal(getcolors("L", 128), None) self.assertEqual(getcolors("1"), 2)
assert_equal(getcolors("L", 1024), 193) self.assertEqual(getcolors("L"), 193)
self.assertEqual(getcolors("I"), 193)
self.assertEqual(getcolors("F"), 193)
self.assertEqual(getcolors("P"), 54) # fixed palette
self.assertEqual(getcolors("RGB"), None)
self.assertEqual(getcolors("RGBA"), None)
self.assertEqual(getcolors("CMYK"), None)
self.assertEqual(getcolors("YCbCr"), None)
assert_equal(getcolors("RGB", 8192), None) self.assertEqual(getcolors("L", 128), None)
assert_equal(getcolors("RGB", 16384), 14836) self.assertEqual(getcolors("L", 1024), 193)
assert_equal(getcolors("RGB", 100000), 14836)
assert_equal(getcolors("RGBA", 16384), 14836) self.assertEqual(getcolors("RGB", 8192), None)
assert_equal(getcolors("CMYK", 16384), 14836) self.assertEqual(getcolors("RGB", 16384), 14836)
assert_equal(getcolors("YCbCr", 16384), 11995) self.assertEqual(getcolors("RGB", 100000), 14836)
# -------------------------------------------------------------------- self.assertEqual(getcolors("RGBA", 16384), 14836)
self.assertEqual(getcolors("CMYK", 16384), 14836)
self.assertEqual(getcolors("YCbCr", 16384), 11995)
def test_pack(): # --------------------------------------------------------------------
# Pack problems for small tables (@PIL209)
im = lena().quantize(3).convert("RGB") def test_pack(self):
# Pack problems for small tables (@PIL209)
expected = [(3236, (227, 183, 147)), (6297, (143, 84, 81)), (6851, (208, 143, 112))] im = lena().quantize(3).convert("RGB")
A = im.getcolors(maxcolors=2) expected = [
assert_equal(A, None) (3236, (227, 183, 147)),
(6297, (143, 84, 81)),
(6851, (208, 143, 112))]
A = im.getcolors(maxcolors=3) A = im.getcolors(maxcolors=2)
A.sort() self.assertEqual(A, None)
assert_equal(A, expected)
A = im.getcolors(maxcolors=4) A = im.getcolors(maxcolors=3)
A.sort() A.sort()
assert_equal(A, expected) self.assertEqual(A, expected)
A = im.getcolors(maxcolors=8) A = im.getcolors(maxcolors=4)
A.sort() A.sort()
assert_equal(A, expected) self.assertEqual(A, expected)
A = im.getcolors(maxcolors=16) A = im.getcolors(maxcolors=8)
A.sort() A.sort()
assert_equal(A, expected) self.assertEqual(A, expected)
A = im.getcolors(maxcolors=16)
A.sort()
self.assertEqual(A, expected)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,28 +1,35 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_sanity(): class TestImageGetData(PillowTestCase):
data = lena().getdata() def test_sanity(self):
assert_no_exception(lambda: len(data)) data = lena().getdata()
assert_no_exception(lambda: list(data))
assert_equal(data[0], (223, 162, 133)) len(data)
list(data)
def test_roundtrip(): self.assertEqual(data[0], (223, 162, 133))
def getdata(mode): def test_roundtrip(self):
im = lena(mode).resize((32, 30))
data = im.getdata()
return data[0], len(data), len(list(data))
assert_equal(getdata("1"), (255, 960, 960)) def getdata(mode):
assert_equal(getdata("L"), (176, 960, 960)) im = lena(mode).resize((32, 30))
assert_equal(getdata("I"), (176, 960, 960)) data = im.getdata()
assert_equal(getdata("F"), (176.0, 960, 960)) return data[0], len(data), len(list(data))
assert_equal(getdata("RGB"), ((223, 162, 133), 960, 960))
assert_equal(getdata("RGBA"), ((223, 162, 133, 255), 960, 960)) self.assertEqual(getdata("1"), (255, 960, 960))
assert_equal(getdata("CMYK"), ((32, 93, 122, 0), 960, 960)) self.assertEqual(getdata("L"), (176, 960, 960))
assert_equal(getdata("YCbCr"), ((176, 103, 160), 960, 960)) self.assertEqual(getdata("I"), (176, 960, 960))
self.assertEqual(getdata("F"), (176.0, 960, 960))
self.assertEqual(getdata("RGB"), ((223, 162, 133), 960, 960))
self.assertEqual(getdata("RGBA"), ((223, 162, 133, 255), 960, 960))
self.assertEqual(getdata("CMYK"), ((32, 93, 122, 0), 960, 960))
self.assertEqual(getdata("YCbCr"), ((176, 103, 160), 960, 960))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,17 +1,27 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_extrema(): class TestImageGetExtrema(PillowTestCase):
def extrema(mode): def test_extrema(self):
return lena(mode).getextrema()
assert_equal(extrema("1"), (0, 255)) def extrema(mode):
assert_equal(extrema("L"), (40, 235)) return lena(mode).getextrema()
assert_equal(extrema("I"), (40, 235))
assert_equal(extrema("F"), (40.0, 235.0)) self.assertEqual(extrema("1"), (0, 255))
assert_equal(extrema("P"), (11, 218)) # fixed palette self.assertEqual(extrema("L"), (40, 235))
assert_equal(extrema("RGB"), ((61, 255), (26, 234), (44, 223))) self.assertEqual(extrema("I"), (40, 235))
assert_equal(extrema("RGBA"), ((61, 255), (26, 234), (44, 223), (255, 255))) self.assertEqual(extrema("F"), (40.0, 235.0))
assert_equal(extrema("CMYK"), ((0, 194), (21, 229), (32, 211), (0, 0))) self.assertEqual(extrema("P"), (11, 218)) # fixed palette
self.assertEqual(
extrema("RGB"), ((61, 255), (26, 234), (44, 223)))
self.assertEqual(
extrema("RGBA"), ((61, 255), (26, 234), (44, 223), (255, 255)))
self.assertEqual(
extrema("CMYK"), ((0, 194), (21, 229), (32, 211), (0, 0)))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,14 +1,19 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena, py3
from PIL import Image
def test_sanity(): class TestImageGetIm(PillowTestCase):
im = lena() def test_sanity(self):
type_repr = repr(type(im.getim())) im = lena()
type_repr = repr(type(im.getim()))
if py3: if py3:
assert_true("PyCapsule" in type_repr) self.assertIn("PyCapsule", type_repr)
assert_true(isinstance(im.im.id, int)) self.assertIsInstance(im.im.id, int)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,19 +1,26 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_palette(): class TestImageGetPalette(PillowTestCase):
def palette(mode):
p = lena(mode).getpalette() def test_palette(self):
if p: def palette(mode):
return p[:10] p = lena(mode).getpalette()
return None if p:
assert_equal(palette("1"), None) return p[:10]
assert_equal(palette("L"), None) return None
assert_equal(palette("I"), None) self.assertEqual(palette("1"), None)
assert_equal(palette("F"), None) self.assertEqual(palette("L"), None)
assert_equal(palette("P"), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) self.assertEqual(palette("I"), None)
assert_equal(palette("RGB"), None) self.assertEqual(palette("F"), None)
assert_equal(palette("RGBA"), None) self.assertEqual(palette("P"), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert_equal(palette("CMYK"), None) self.assertEqual(palette("RGB"), None)
assert_equal(palette("YCbCr"), None) self.assertEqual(palette("RGBA"), None)
self.assertEqual(palette("CMYK"), None)
self.assertEqual(palette("YCbCr"), None)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,8 +1,9 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
Image.USE_CFFI_ACCESS=False Image.USE_CFFI_ACCESS = False
def color(mode): def color(mode):
bands = Image.getmodebands(mode) bands = Image.getmodebands(mode)
@ -12,38 +13,41 @@ def color(mode):
return tuple(range(1, bands+1)) return tuple(range(1, bands+1))
class TestImageGetPixel(PillowTestCase):
def check(mode, c=None): def check(self, mode, c=None):
if not c: if not c:
c = color(mode) c = color(mode)
#check putpixel # check putpixel
im = Image.new(mode, (1, 1), None) im = Image.new(mode, (1, 1), None)
im.putpixel((0, 0), c) im.putpixel((0, 0), c)
assert_equal(im.getpixel((0, 0)), c, self.assertEqual(
"put/getpixel roundtrip failed for mode %s, color %s" % im.getpixel((0, 0)), c,
(mode, c)) "put/getpixel roundtrip failed for mode %s, color %s" % (mode, c))
# check inital color # check inital color
im = Image.new(mode, (1, 1), c) im = Image.new(mode, (1, 1), c)
assert_equal(im.getpixel((0, 0)), c, self.assertEqual(
"initial color failed for mode %s, color %s " % im.getpixel((0, 0)), c,
(mode, color)) "initial color failed for mode %s, color %s " % (mode, color))
def test_basic(): def test_basic(self):
for mode in ("1", "L", "LA", "I", "I;16", "I;16B", "F", for mode in ("1", "L", "LA", "I", "I;16", "I;16B", "F",
"P", "PA", "RGB", "RGBA", "RGBX", "CMYK","YCbCr"): "P", "PA", "RGB", "RGBA", "RGBX", "CMYK", "YCbCr"):
check(mode) self.check(mode)
def test_signedness():
# see https://github.com/python-pillow/Pillow/issues/452
# pixelaccess is using signed int* instead of uint*
for mode in ("I;16", "I;16B"):
check(mode, 2**15-1)
check(mode, 2**15)
check(mode, 2**15+1)
check(mode, 2**16-1)
def test_signedness(self):
# see https://github.com/python-pillow/Pillow/issues/452
# pixelaccess is using signed int* instead of uint*
for mode in ("I;16", "I;16B"):
self.check(mode, 2**15-1)
self.check(mode, 2**15)
self.check(mode, 2**15+1)
self.check(mode, 2**16-1)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,30 +1,38 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_sanity():
im = lena() class TestImageGetProjection(PillowTestCase):
projection = im.getprojection() def test_sanity(self):
assert_equal(len(projection), 2) im = lena()
assert_equal(len(projection[0]), im.size[0])
assert_equal(len(projection[1]), im.size[1])
# 8-bit image projection = im.getprojection()
im = Image.new("L", (10, 10))
assert_equal(im.getprojection()[0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert_equal(im.getprojection()[1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
im.paste(255, (2, 4, 8, 6))
assert_equal(im.getprojection()[0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0])
assert_equal(im.getprojection()[1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0])
# 32-bit image self.assertEqual(len(projection), 2)
im = Image.new("RGB", (10, 10)) self.assertEqual(len(projection[0]), im.size[0])
assert_equal(im.getprojection()[0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) self.assertEqual(len(projection[1]), im.size[1])
assert_equal(im.getprojection()[1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
im.paste(255, (2, 4, 8, 6))
assert_equal(im.getprojection()[0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0])
assert_equal(im.getprojection()[1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0])
# 8-bit image
im = Image.new("L", (10, 10))
self.assertEqual(im.getprojection()[0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
self.assertEqual(im.getprojection()[1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
im.paste(255, (2, 4, 8, 6))
self.assertEqual(im.getprojection()[0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0])
self.assertEqual(im.getprojection()[1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0])
# 32-bit image
im = Image.new("RGB", (10, 10))
self.assertEqual(im.getprojection()[0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
self.assertEqual(im.getprojection()[1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
im.paste(255, (2, 4, 8, 6))
self.assertEqual(im.getprojection()[0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0])
self.assertEqual(im.getprojection()[1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0])
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,19 +1,26 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_histogram(): class TestImageHistogram(PillowTestCase):
def histogram(mode): def test_histogram(self):
h = lena(mode).histogram()
return len(h), min(h), max(h)
assert_equal(histogram("1"), (256, 0, 8872)) def histogram(mode):
assert_equal(histogram("L"), (256, 0, 199)) h = lena(mode).histogram()
assert_equal(histogram("I"), (256, 0, 199)) return len(h), min(h), max(h)
assert_equal(histogram("F"), (256, 0, 199))
assert_equal(histogram("P"), (256, 0, 2912)) self.assertEqual(histogram("1"), (256, 0, 8872))
assert_equal(histogram("RGB"), (768, 0, 285)) self.assertEqual(histogram("L"), (256, 0, 199))
assert_equal(histogram("RGBA"), (1024, 0, 16384)) self.assertEqual(histogram("I"), (256, 0, 199))
assert_equal(histogram("CMYK"), (1024, 0, 16384)) self.assertEqual(histogram("F"), (256, 0, 199))
assert_equal(histogram("YCbCr"), (768, 0, 741)) self.assertEqual(histogram("P"), (256, 0, 2912))
self.assertEqual(histogram("RGB"), (768, 0, 285))
self.assertEqual(histogram("RGBA"), (1024, 0, 16384))
self.assertEqual(histogram("CMYK"), (1024, 0, 16384))
self.assertEqual(histogram("YCbCr"), (768, 0, 741))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,27 +1,35 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
import os import os
def test_sanity():
im = lena() class TestImageLoad(PillowTestCase):
pix = im.load() def test_sanity(self):
assert_equal(pix[0, 0], (223, 162, 133)) im = lena()
def test_close(): pix = im.load()
im = Image.open("Images/lena.gif")
assert_no_exception(lambda: im.close())
assert_exception(ValueError, lambda: im.load())
assert_exception(ValueError, lambda: im.getpixel((0,0)))
def test_contextmanager(): self.assertEqual(pix[0, 0], (223, 162, 133))
fn = None
with Image.open("Images/lena.gif") as im:
fn = im.fp.fileno()
assert_no_exception(lambda: os.fstat(fn))
assert_exception(OSError, lambda: os.fstat(fn)) def test_close(self):
im = Image.open("Images/lena.gif")
im.close()
self.assertRaises(ValueError, lambda: im.load())
self.assertRaises(ValueError, lambda: im.getpixel((0, 0)))
def test_contextmanager(self):
fn = None
with Image.open("Images/lena.gif") as im:
fn = im.fp.fileno()
os.fstat(fn)
self.assertRaises(OSError, lambda: os.fstat(fn))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,27 +1,36 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_sanity():
im = lena() class TestImageMode(PillowTestCase):
assert_no_exception(lambda: im.mode)
def test_properties(): def test_sanity(self):
def check(mode, *result):
signature = ( im = lena()
Image.getmodebase(mode), Image.getmodetype(mode), im.mode
Image.getmodebands(mode), Image.getmodebandnames(mode),
) def test_properties(self):
assert_equal(signature, result) def check(mode, *result):
check("1", "L", "L", 1, ("1",)) signature = (
check("L", "L", "L", 1, ("L",)) Image.getmodebase(mode), Image.getmodetype(mode),
check("P", "RGB", "L", 1, ("P",)) Image.getmodebands(mode), Image.getmodebandnames(mode),
check("I", "L", "I", 1, ("I",)) )
check("F", "L", "F", 1, ("F",)) self.assertEqual(signature, result)
check("RGB", "RGB", "L", 3, ("R", "G", "B")) check("1", "L", "L", 1, ("1",))
check("RGBA", "RGB", "L", 4, ("R", "G", "B", "A")) check("L", "L", "L", 1, ("L",))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X")) check("P", "RGB", "L", 1, ("P",))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X")) check("I", "L", "I", 1, ("I",))
check("CMYK", "RGB", "L", 4, ("C", "M", "Y", "K")) check("F", "L", "F", 1, ("F",))
check("YCbCr", "RGB", "L", 3, ("Y", "Cb", "Cr")) check("RGB", "RGB", "L", 3, ("R", "G", "B"))
check("RGBA", "RGB", "L", 4, ("R", "G", "B", "A"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("CMYK", "RGB", "L", 4, ("C", "M", "Y", "K"))
check("YCbCr", "RGB", "L", 3, ("Y", "Cb", "Cr"))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,16 +1,25 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_offset(): class TestImageOffset(PillowTestCase):
im1 = lena() def test_offset(self):
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10)) im1 = lena()
assert_equal(im1.getpixel((0, 0)), im2.getpixel((10, 10)))
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10, 20)) im2 = self.assert_warning(DeprecationWarning, lambda: im1.offset(10))
assert_equal(im1.getpixel((0, 0)), im2.getpixel((10, 20))) self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((10, 10)))
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(20, 20)) im2 = self.assert_warning(
assert_equal(im1.getpixel((0, 0)), im2.getpixel((20, 20))) DeprecationWarning, lambda: im1.offset(10, 20))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((10, 20)))
im2 = self.assert_warning(
DeprecationWarning, lambda: im1.offset(20, 20))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((20, 20)))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,33 +1,41 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image import sys
if hasattr(sys, 'pypy_version_info'):
# This takes _forever_ on pypy. Open Bug,
# see https://github.com/python-pillow/Pillow/issues/484
skip()
def test_sanity():
im = lena()
assert_exception(ValueError, lambda: im.point(list(range(256))))
assert_no_exception(lambda: im.point(list(range(256))*3))
assert_no_exception(lambda: im.point(lambda x: x))
im = im.convert("I")
assert_exception(ValueError, lambda: im.point(list(range(256))))
assert_no_exception(lambda: im.point(lambda x: x*1))
assert_no_exception(lambda: im.point(lambda x: x+1))
assert_no_exception(lambda: im.point(lambda x: x*1+1))
assert_exception(TypeError, lambda: im.point(lambda x: x-1))
assert_exception(TypeError, lambda: im.point(lambda x: x/1))
def test_16bit_lut(): class TestImagePoint(PillowTestCase):
""" Tests for 16 bit -> 8 bit lut for converting I->L images
see https://github.com/python-pillow/Pillow/issues/440
"""
im = lena("I") def setUp(self):
assert_no_exception(lambda: im.point(list(range(256))*256, 'L')) if hasattr(sys, 'pypy_version_info'):
# This takes _forever_ on PyPy. Open Bug,
# see https://github.com/python-pillow/Pillow/issues/484
self.skipTest("Too slow on PyPy")
def test_sanity(self):
im = lena()
self.assertRaises(ValueError, lambda: im.point(list(range(256))))
im.point(list(range(256))*3)
im.point(lambda x: x)
im = im.convert("I")
self.assertRaises(ValueError, lambda: im.point(list(range(256))))
im.point(lambda x: x*1)
im.point(lambda x: x+1)
im.point(lambda x: x*1+1)
self.assertRaises(TypeError, lambda: im.point(lambda x: x-1))
self.assertRaises(TypeError, lambda: im.point(lambda x: x/1))
def test_16bit_lut(self):
""" Tests for 16 bit -> 8 bit lut for converting I->L images
see https://github.com/python-pillow/Pillow/issues/440
"""
im = lena("I")
im.point(list(range(256))*256, 'L')
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,43 +1,52 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
def test_interface():
im = Image.new("RGBA", (1, 1), (1, 2, 3, 0)) class TestImagePutAlpha(PillowTestCase):
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 0))
im = Image.new("RGBA", (1, 1), (1, 2, 3)) def test_interface(self):
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 255))
im.putalpha(Image.new("L", im.size, 4)) im = Image.new("RGBA", (1, 1), (1, 2, 3, 0))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4)) self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 0))
im.putalpha(5) im = Image.new("RGBA", (1, 1), (1, 2, 3))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 5)) self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 255))
def test_promote(): im.putalpha(Image.new("L", im.size, 4))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
im = Image.new("L", (1, 1), 1) im.putalpha(5)
assert_equal(im.getpixel((0, 0)), 1) self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 5))
im.putalpha(2) def test_promote(self):
assert_equal(im.mode, 'LA')
assert_equal(im.getpixel((0, 0)), (1, 2))
im = Image.new("RGB", (1, 1), (1, 2, 3)) im = Image.new("L", (1, 1), 1)
assert_equal(im.getpixel((0, 0)), (1, 2, 3)) self.assertEqual(im.getpixel((0, 0)), 1)
im.putalpha(4) im.putalpha(2)
assert_equal(im.mode, 'RGBA') self.assertEqual(im.mode, 'LA')
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4)) self.assertEqual(im.getpixel((0, 0)), (1, 2))
def test_readonly(): im = Image.new("RGB", (1, 1), (1, 2, 3))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3))
im = Image.new("RGB", (1, 1), (1, 2, 3)) im.putalpha(4)
im.readonly = 1 self.assertEqual(im.mode, 'RGBA')
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
im.putalpha(4) def test_readonly(self):
assert_false(im.readonly)
assert_equal(im.mode, 'RGBA') im = Image.new("RGB", (1, 1), (1, 2, 3))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4)) im.readonly = 1
im.putalpha(4)
self.assertFalse(im.readonly)
self.assertEqual(im.mode, 'RGBA')
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,40 +1,48 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
import sys import sys
from PIL import Image from PIL import Image
def test_sanity():
im1 = lena() class TestImagePutData(PillowTestCase):
data = list(im1.getdata()) def test_sanity(self):
im2 = Image.new(im1.mode, im1.size, 0) im1 = lena()
im2.putdata(data)
assert_image_equal(im1, im2) data = list(im1.getdata())
# readonly im2 = Image.new(im1.mode, im1.size, 0)
im2 = Image.new(im1.mode, im2.size, 0) im2.putdata(data)
im2.readonly = 1
im2.putdata(data)
assert_false(im2.readonly) self.assert_image_equal(im1, im2)
assert_image_equal(im1, im2)
# readonly
im2 = Image.new(im1.mode, im2.size, 0)
im2.readonly = 1
im2.putdata(data)
self.assertFalse(im2.readonly)
self.assert_image_equal(im1, im2)
def test_long_integers(self):
# see bug-200802-systemerror
def put(value):
im = Image.new("RGBA", (1, 1))
im.putdata([value])
return im.getpixel((0, 0))
self.assertEqual(put(0xFFFFFFFF), (255, 255, 255, 255))
self.assertEqual(put(0xFFFFFFFF), (255, 255, 255, 255))
self.assertEqual(put(-1), (255, 255, 255, 255))
self.assertEqual(put(-1), (255, 255, 255, 255))
if sys.maxsize > 2**32:
self.assertEqual(put(sys.maxsize), (255, 255, 255, 255))
else:
self.assertEqual(put(sys.maxsize), (255, 255, 255, 127))
def test_long_integers(): if __name__ == '__main__':
# see bug-200802-systemerror unittest.main()
def put(value):
im = Image.new("RGBA", (1, 1)) # End of file
im.putdata([value])
return im.getpixel((0, 0))
assert_equal(put(0xFFFFFFFF), (255, 255, 255, 255))
assert_equal(put(0xFFFFFFFF), (255, 255, 255, 255))
assert_equal(put(-1), (255, 255, 255, 255))
assert_equal(put(-1), (255, 255, 255, 255))
if sys.maxsize > 2**32:
assert_equal(put(sys.maxsize), (255, 255, 255, 255))
else:
assert_equal(put(sys.maxsize), (255, 255, 255, 127))

View File

@ -1,28 +1,36 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
from PIL import ImagePalette from PIL import ImagePalette
def test_putpalette():
def palette(mode):
im = lena(mode).copy()
im.putpalette(list(range(256))*3)
p = im.getpalette()
if p:
return im.mode, p[:10]
return im.mode
assert_exception(ValueError, lambda: palette("1"))
assert_equal(palette("L"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
assert_equal(palette("P"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
assert_exception(ValueError, lambda: palette("I"))
assert_exception(ValueError, lambda: palette("F"))
assert_exception(ValueError, lambda: palette("RGB"))
assert_exception(ValueError, lambda: palette("RGBA"))
assert_exception(ValueError, lambda: palette("YCbCr"))
def test_imagepalette(): class TestImagePutPalette(PillowTestCase):
im = lena("P")
assert_no_exception(lambda: im.putpalette(ImagePalette.negative())) def test_putpalette(self):
assert_no_exception(lambda: im.putpalette(ImagePalette.random())) def palette(mode):
assert_no_exception(lambda: im.putpalette(ImagePalette.sepia())) im = lena(mode).copy()
assert_no_exception(lambda: im.putpalette(ImagePalette.wedge())) im.putpalette(list(range(256))*3)
p = im.getpalette()
if p:
return im.mode, p[:10]
return im.mode
self.assertRaises(ValueError, lambda: palette("1"))
self.assertEqual(palette("L"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
self.assertEqual(palette("P"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
self.assertRaises(ValueError, lambda: palette("I"))
self.assertRaises(ValueError, lambda: palette("F"))
self.assertRaises(ValueError, lambda: palette("RGB"))
self.assertRaises(ValueError, lambda: palette("RGBA"))
self.assertRaises(ValueError, lambda: palette("YCbCr"))
def test_imagepalette(self):
im = lena("P")
im.putpalette(ImagePalette.negative())
im.putpalette(ImagePalette.random())
im.putpalette(ImagePalette.sepia())
im.putpalette(ImagePalette.wedge())
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,45 +1,50 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
Image.USE_CFFI_ACCESS=False Image.USE_CFFI_ACCESS = False
def test_sanity():
im1 = lena()
im2 = Image.new(im1.mode, im1.size, 0)
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
im2.readonly = 1
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
assert_false(im2.readonly)
assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
pix1 = im1.load()
pix2 = im2.load()
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pix2[x, y] = pix1[x, y]
assert_image_equal(im1, im2)
class TestImagePutPixel(PillowTestCase):
def test_sanity(self):
im1 = lena()
im2 = Image.new(im1.mode, im1.size, 0)
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
self.assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
im2.readonly = 1
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
self.assertFalse(im2.readonly)
self.assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
pix1 = im1.load()
pix2 = im2.load()
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pix2[x, y] = pix1[x, y]
self.assert_image_equal(im1, im2)
# see test_image_getpixel for more tests
# see test_image_getpixel for more tests if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,27 +1,35 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_sanity():
im = lena() class TestImageQuantize(PillowTestCase):
im = im.quantize() def test_sanity(self):
assert_image(im, "P", im.size) im = lena()
im = lena() im = im.quantize()
im = im.quantize(palette=lena("P")) self.assert_image(im, "P", im.size)
assert_image(im, "P", im.size)
def test_octree_quantize(): im = lena()
im = lena() im = im.quantize(palette=lena("P"))
self.assert_image(im, "P", im.size)
im = im.quantize(100, Image.FASTOCTREE) def test_octree_quantize(self):
assert_image(im, "P", im.size) im = lena()
assert len(im.getcolors()) == 100 im = im.quantize(100, Image.FASTOCTREE)
self.assert_image(im, "P", im.size)
def test_rgba_quantize(): assert len(im.getcolors()) == 100
im = lena('RGBA')
assert_no_exception(lambda: im.quantize()) def test_rgba_quantize(self):
assert_exception(Exception, lambda: im.quantize(method=0)) im = lena('RGBA')
im.quantize()
self.assertRaises(Exception, lambda: im.quantize(method=0))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,12 +1,19 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_resize(): class TestImageResize(PillowTestCase):
def resize(mode, size):
out = lena(mode).resize(size) def test_resize(self):
assert_equal(out.mode, mode) def resize(mode, size):
assert_equal(out.size, size) out = lena(mode).resize(size)
for mode in "1", "P", "L", "RGB", "I", "F": self.assertEqual(out.mode, mode)
yield_test(resize, mode, (100, 100)) self.assertEqual(out.size, size)
yield_test(resize, mode, (200, 200)) for mode in "1", "P", "L", "RGB", "I", "F":
resize(mode, (100, 100))
resize(mode, (200, 200))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,15 +1,22 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_rotate(): class TestImageRotate(PillowTestCase):
def rotate(mode):
im = lena(mode) def test_rotate(self):
out = im.rotate(45) def rotate(mode):
assert_equal(out.mode, mode) im = lena(mode)
assert_equal(out.size, im.size) # default rotate clips output out = im.rotate(45)
out = im.rotate(45, expand=1) self.assertEqual(out.mode, mode)
assert_equal(out.mode, mode) self.assertEqual(out.size, im.size) # default rotate clips output
assert_true(out.size != im.size) out = im.rotate(45, expand=1)
for mode in "1", "P", "L", "RGB", "I", "F": self.assertEqual(out.mode, mode)
yield_test(rotate, mode) self.assertNotEqual(out.size, im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
rotate(mode)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,49 +1,67 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_split():
def split(mode):
layers = lena(mode).split()
return [(i.mode, i.size[0], i.size[1]) for i in layers]
assert_equal(split("1"), [('1', 128, 128)])
assert_equal(split("L"), [('L', 128, 128)])
assert_equal(split("I"), [('I', 128, 128)])
assert_equal(split("F"), [('F', 128, 128)])
assert_equal(split("P"), [('P', 128, 128)])
assert_equal(split("RGB"), [('L', 128, 128), ('L', 128, 128), ('L', 128, 128)])
assert_equal(split("RGBA"), [('L', 128, 128), ('L', 128, 128), ('L', 128, 128), ('L', 128, 128)])
assert_equal(split("CMYK"), [('L', 128, 128), ('L', 128, 128), ('L', 128, 128), ('L', 128, 128)])
assert_equal(split("YCbCr"), [('L', 128, 128), ('L', 128, 128), ('L', 128, 128)])
def test_split_merge(): class TestImageSplit(PillowTestCase):
def split_merge(mode):
return Image.merge(mode, lena(mode).split())
assert_image_equal(lena("1"), split_merge("1"))
assert_image_equal(lena("L"), split_merge("L"))
assert_image_equal(lena("I"), split_merge("I"))
assert_image_equal(lena("F"), split_merge("F"))
assert_image_equal(lena("P"), split_merge("P"))
assert_image_equal(lena("RGB"), split_merge("RGB"))
assert_image_equal(lena("RGBA"), split_merge("RGBA"))
assert_image_equal(lena("CMYK"), split_merge("CMYK"))
assert_image_equal(lena("YCbCr"), split_merge("YCbCr"))
def test_split_open(): def test_split(self):
codecs = dir(Image.core) def split(mode):
layers = lena(mode).split()
return [(i.mode, i.size[0], i.size[1]) for i in layers]
self.assertEqual(split("1"), [('1', 128, 128)])
self.assertEqual(split("L"), [('L', 128, 128)])
self.assertEqual(split("I"), [('I', 128, 128)])
self.assertEqual(split("F"), [('F', 128, 128)])
self.assertEqual(split("P"), [('P', 128, 128)])
self.assertEqual(
split("RGB"), [('L', 128, 128), ('L', 128, 128), ('L', 128, 128)])
self.assertEqual(
split("RGBA"),
[('L', 128, 128), ('L', 128, 128),
('L', 128, 128), ('L', 128, 128)])
self.assertEqual(
split("CMYK"),
[('L', 128, 128), ('L', 128, 128),
('L', 128, 128), ('L', 128, 128)])
self.assertEqual(
split("YCbCr"),
[('L', 128, 128), ('L', 128, 128), ('L', 128, 128)])
if 'zip_encoder' in codecs: def test_split_merge(self):
file = tempfile("temp.png") def split_merge(mode):
else: return Image.merge(mode, lena(mode).split())
file = tempfile("temp.pcx") self.assert_image_equal(lena("1"), split_merge("1"))
self.assert_image_equal(lena("L"), split_merge("L"))
self.assert_image_equal(lena("I"), split_merge("I"))
self.assert_image_equal(lena("F"), split_merge("F"))
self.assert_image_equal(lena("P"), split_merge("P"))
self.assert_image_equal(lena("RGB"), split_merge("RGB"))
self.assert_image_equal(lena("RGBA"), split_merge("RGBA"))
self.assert_image_equal(lena("CMYK"), split_merge("CMYK"))
self.assert_image_equal(lena("YCbCr"), split_merge("YCbCr"))
def split_open(mode): def test_split_open(self):
lena(mode).save(file) codecs = dir(Image.core)
im = Image.open(file)
return len(im.split()) if 'zip_encoder' in codecs:
assert_equal(split_open("1"), 1) file = self.tempfile("temp.png")
assert_equal(split_open("L"), 1) else:
assert_equal(split_open("P"), 1) file = self.tempfile("temp.pcx")
assert_equal(split_open("RGB"), 3)
if 'zip_encoder' in codecs: def split_open(mode):
assert_equal(split_open("RGBA"), 4) lena(mode).save(file)
im = Image.open(file)
return len(im.split())
self.assertEqual(split_open("1"), 1)
self.assertEqual(split_open("L"), 1)
self.assertEqual(split_open("P"), 1)
self.assertEqual(split_open("RGB"), 3)
if 'zip_encoder' in codecs:
self.assertEqual(split_open("RGBA"), 4)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,36 +1,43 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
def test_sanity(): class TestImageThumbnail(PillowTestCase):
im = lena() def test_sanity(self):
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100)) im = lena()
im.thumbnail((100, 100))
def test_aspect(): self.assert_image(im, im.mode, (100, 100))
im = lena() def test_aspect(self):
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100))
im = lena().resize((128, 256)) im = lena()
im.thumbnail((100, 100)) im.thumbnail((100, 100))
assert_image(im, im.mode, (50, 100)) self.assert_image(im, im.mode, (100, 100))
im = lena().resize((128, 256)) im = lena().resize((128, 256))
im.thumbnail((50, 100)) im.thumbnail((100, 100))
assert_image(im, im.mode, (50, 100)) self.assert_image(im, im.mode, (50, 100))
im = lena().resize((256, 128)) im = lena().resize((128, 256))
im.thumbnail((100, 100)) im.thumbnail((50, 100))
assert_image(im, im.mode, (100, 50)) self.assert_image(im, im.mode, (50, 100))
im = lena().resize((256, 128)) im = lena().resize((256, 128))
im.thumbnail((100, 50)) im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 50)) self.assert_image(im, im.mode, (100, 50))
im = lena().resize((128, 128)) im = lena().resize((256, 128))
im.thumbnail((100, 100)) im.thumbnail((100, 50))
assert_image(im, im.mode, (100, 100)) self.assert_image(im, im.mode, (100, 50))
im = lena().resize((128, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,15 +1,22 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena, fromstring
from PIL import Image
def test_sanity(): class TestImageToBitmap(PillowTestCase):
assert_exception(ValueError, lambda: lena().tobitmap()) def test_sanity(self):
assert_no_exception(lambda: lena().convert("1").tobitmap())
im1 = lena().convert("1") self.assertRaises(ValueError, lambda: lena().tobitmap())
lena().convert("1").tobitmap()
bitmap = im1.tobitmap() im1 = lena().convert("1")
assert_true(isinstance(bitmap, bytes)) bitmap = im1.tobitmap()
assert_image_equal(im1, fromstring(bitmap))
self.assertIsInstance(bitmap, bytes)
self.assert_image_equal(im1, fromstring(bitmap))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,7 +1,13 @@
from tester import * from helper import unittest, lena
from PIL import Image
def test_sanity(): class TestImageToBytes(unittest.TestCase):
data = lena().tobytes()
assert_true(isinstance(data, bytes)) def test_sanity(self):
data = lena().tobytes()
self.assertTrue(isinstance(data, bytes))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,116 +1,125 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def test_extent():
im = lena('RGB') class TestImageTransform(PillowTestCase):
(w,h) = im.size
transformed = im.transform(im.size, Image.EXTENT, def test_extent(self):
(0,0, im = lena('RGB')
w//2,h//2), # ul -> lr (w, h) = im.size
Image.BILINEAR) transformed = im.transform(im.size, Image.EXTENT,
(0, 0,
w//2, h//2), # ul -> lr
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0, 0, w, h))
# undone -- precision?
self.assert_image_similar(transformed, scaled, 10)
def test_quad(self):
# one simple quad transform, equivalent to scale & crop upper left quad
im = lena('RGB')
(w, h) = im.size
transformed = im.transform(im.size, Image.QUAD,
(0, 0, 0, h//2,
# ul -> ccw around quad:
w//2, h//2, w//2, 0),
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0, 0, w, h))
self.assert_image_equal(transformed, scaled)
def test_mesh(self):
# this should be a checkerboard of halfsized lenas in ul, lr
im = lena('RGBA')
(w, h) = im.size
transformed = im.transform(im.size, Image.MESH,
[((0, 0, w//2, h//2), # box
(0, 0, 0, h,
w, h, w, 0)), # ul -> ccw around quad
((w//2, h//2, w, h), # box
(0, 0, 0, h,
w, h, w, 0))], # ul -> ccw around quad
Image.BILINEAR)
# transformed.save('transformed.png')
scaled = im.resize((w//2, h//2), Image.BILINEAR)
checker = Image.new('RGBA', im.size)
checker.paste(scaled, (0, 0))
checker.paste(scaled, (w//2, h//2))
self.assert_image_equal(transformed, checker)
# now, check to see that the extra area is (0, 0, 0, 0)
blank = Image.new('RGBA', (w//2, h//2), (0, 0, 0, 0))
self.assert_image_equal(blank, transformed.crop((w//2, 0, w, h//2)))
self.assert_image_equal(blank, transformed.crop((0, h//2, w//2, h)))
def _test_alpha_premult(self, op):
# create image with half white, half black,
# with the black half transparent.
# do op,
# there should be no darkness in the white section.
im = Image.new('RGBA', (10, 10), (0, 0, 0, 0))
im2 = Image.new('RGBA', (5, 10), (255, 255, 255, 255))
im.paste(im2, (0, 0))
im = op(im, (40, 10))
im_background = Image.new('RGB', (40, 10), (255, 255, 255))
im_background.paste(im, (0, 0), im)
hist = im_background.histogram()
self.assertEqual(40*10, hist[-1])
def test_alpha_premult_resize(self):
def op(im, sz):
return im.resize(sz, Image.LINEAR)
self._test_alpha_premult(op)
def test_alpha_premult_transform(self):
def op(im, sz):
(w, h) = im.size
return im.transform(sz, Image.EXTENT,
(0, 0,
w, h),
Image.BILINEAR)
self._test_alpha_premult(op)
def test_blank_fill(self):
# attempting to hit
# https://github.com/python-pillow/Pillow/issues/254 reported
#
# issue is that transforms with transparent overflow area
# contained junk from previous images, especially on systems with
# constrained memory. So, attempt to fill up memory with a
# pattern, free it, and then run the mesh test again. Using a 1Mp
# image with 4 bands, for 4 megs of data allocated, x 64. OMM (64
# bit 12.04 VM with 512 megs available, this fails with Pillow <
# a0eaf06cc5f62a6fb6de556989ac1014ff3348ea
#
# Running by default, but I'd totally understand not doing it in
# the future
foo = [Image.new('RGBA', (1024, 1024), (a, a, a, a))
for a in range(1, 65)]
# Yeah. Watch some JIT optimize this out.
foo = None
self.test_mesh()
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0,0,w,h)) if __name__ == '__main__':
unittest.main()
assert_image_similar(transformed, scaled, 10) # undone -- precision? # End of file
def test_quad():
# one simple quad transform, equivalent to scale & crop upper left quad
im = lena('RGB')
(w,h) = im.size
transformed = im.transform(im.size, Image.QUAD,
(0,0,0,h//2,
w//2,h//2,w//2,0), # ul -> ccw around quad
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0,0,w,h))
assert_image_equal(transformed, scaled)
def test_mesh():
# this should be a checkerboard of halfsized lenas in ul, lr
im = lena('RGBA')
(w,h) = im.size
transformed = im.transform(im.size, Image.MESH,
[((0,0,w//2,h//2), # box
(0,0,0,h,
w,h,w,0)), # ul -> ccw around quad
((w//2,h//2,w,h), # box
(0,0,0,h,
w,h,w,0))], # ul -> ccw around quad
Image.BILINEAR)
#transformed.save('transformed.png')
scaled = im.resize((w//2, h//2), Image.BILINEAR)
checker = Image.new('RGBA', im.size)
checker.paste(scaled, (0,0))
checker.paste(scaled, (w//2,h//2))
assert_image_equal(transformed, checker)
# now, check to see that the extra area is (0,0,0,0)
blank = Image.new('RGBA', (w//2,h//2), (0,0,0,0))
assert_image_equal(blank, transformed.crop((w//2,0,w,h//2)))
assert_image_equal(blank, transformed.crop((0,h//2,w//2,h)))
def _test_alpha_premult(op):
# create image with half white, half black, with the black half transparent.
# do op,
# there should be no darkness in the white section.
im = Image.new('RGBA', (10,10), (0,0,0,0));
im2 = Image.new('RGBA', (5,10), (255,255,255,255));
im.paste(im2, (0,0))
im = op(im, (40,10))
im_background = Image.new('RGB', (40,10), (255,255,255))
im_background.paste(im, (0,0), im)
hist = im_background.histogram()
assert_equal(40*10, hist[-1])
def test_alpha_premult_resize():
def op (im, sz):
return im.resize(sz, Image.LINEAR)
_test_alpha_premult(op)
def test_alpha_premult_transform():
def op(im, sz):
(w,h) = im.size
return im.transform(sz, Image.EXTENT,
(0,0,
w,h),
Image.BILINEAR)
_test_alpha_premult(op)
def test_blank_fill():
# attempting to hit
# https://github.com/python-pillow/Pillow/issues/254 reported
#
# issue is that transforms with transparent overflow area
# contained junk from previous images, especially on systems with
# constrained memory. So, attempt to fill up memory with a
# pattern, free it, and then run the mesh test again. Using a 1Mp
# image with 4 bands, for 4 megs of data allocated, x 64. OMM (64
# bit 12.04 VM with 512 megs available, this fails with Pillow <
# a0eaf06cc5f62a6fb6de556989ac1014ff3348ea
#
# Running by default, but I'd totally understand not doing it in
# the future
foo = [Image.new('RGBA',(1024,1024), (a,a,a,a))
for a in range(1,65)]
# Yeah. Watch some JIT optimize this out.
foo = None
test_mesh()

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
@ -8,27 +8,37 @@ ROTATE_90 = Image.ROTATE_90
ROTATE_180 = Image.ROTATE_180 ROTATE_180 = Image.ROTATE_180
ROTATE_270 = Image.ROTATE_270 ROTATE_270 = Image.ROTATE_270
def test_sanity():
im = lena() class TestImageTranspose(PillowTestCase):
assert_no_exception(lambda: im.transpose(FLIP_LEFT_RIGHT)) def test_sanity(self):
assert_no_exception(lambda: im.transpose(FLIP_TOP_BOTTOM))
assert_no_exception(lambda: im.transpose(ROTATE_90)) im = lena()
assert_no_exception(lambda: im.transpose(ROTATE_180))
assert_no_exception(lambda: im.transpose(ROTATE_270))
def test_roundtrip(): im.transpose(FLIP_LEFT_RIGHT)
im.transpose(FLIP_TOP_BOTTOM)
im = lena() im.transpose(ROTATE_90)
im.transpose(ROTATE_180)
im.transpose(ROTATE_270)
def transpose(first, second): def test_roundtrip(self):
return im.transpose(first).transpose(second)
assert_image_equal(im, transpose(FLIP_LEFT_RIGHT, FLIP_LEFT_RIGHT)) im = lena()
assert_image_equal(im, transpose(FLIP_TOP_BOTTOM, FLIP_TOP_BOTTOM))
assert_image_equal(im, transpose(ROTATE_90, ROTATE_270)) def transpose(first, second):
assert_image_equal(im, transpose(ROTATE_180, ROTATE_180)) return im.transpose(first).transpose(second)
self.assert_image_equal(
im, transpose(FLIP_LEFT_RIGHT, FLIP_LEFT_RIGHT))
self.assert_image_equal(
im, transpose(FLIP_TOP_BOTTOM, FLIP_TOP_BOTTOM))
self.assert_image_equal(im, transpose(ROTATE_90, ROTATE_270))
self.assert_image_equal(im, transpose(ROTATE_180, ROTATE_180))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,56 +1,74 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
from PIL import ImageChops from PIL import ImageChops
def test_sanity():
im = lena("L") class TestImageChops(PillowTestCase):
ImageChops.constant(im, 128) def test_sanity(self):
ImageChops.duplicate(im)
ImageChops.invert(im)
ImageChops.lighter(im, im)
ImageChops.darker(im, im)
ImageChops.difference(im, im)
ImageChops.multiply(im, im)
ImageChops.screen(im, im)
ImageChops.add(im, im) im = lena("L")
ImageChops.add(im, im, 2.0)
ImageChops.add(im, im, 2.0, 128)
ImageChops.subtract(im, im)
ImageChops.subtract(im, im, 2.0)
ImageChops.subtract(im, im, 2.0, 128)
ImageChops.add_modulo(im, im) ImageChops.constant(im, 128)
ImageChops.subtract_modulo(im, im) ImageChops.duplicate(im)
ImageChops.invert(im)
ImageChops.lighter(im, im)
ImageChops.darker(im, im)
ImageChops.difference(im, im)
ImageChops.multiply(im, im)
ImageChops.screen(im, im)
ImageChops.blend(im, im, 0.5) ImageChops.add(im, im)
ImageChops.composite(im, im, im) ImageChops.add(im, im, 2.0)
ImageChops.add(im, im, 2.0, 128)
ImageChops.subtract(im, im)
ImageChops.subtract(im, im, 2.0)
ImageChops.subtract(im, im, 2.0, 128)
ImageChops.offset(im, 10) ImageChops.add_modulo(im, im)
ImageChops.offset(im, 10, 20) ImageChops.subtract_modulo(im, im)
def test_logical(): ImageChops.blend(im, im, 0.5)
ImageChops.composite(im, im, im)
def table(op, a, b): ImageChops.offset(im, 10)
out = [] ImageChops.offset(im, 10, 20)
for x in (a, b):
imx = Image.new("1", (1, 1), x)
for y in (a, b):
imy = Image.new("1", (1, 1), y)
out.append(op(imx, imy).getpixel((0, 0)))
return tuple(out)
assert_equal(table(ImageChops.logical_and, 0, 1), (0, 0, 0, 255)) def test_logical(self):
assert_equal(table(ImageChops.logical_or, 0, 1), (0, 255, 255, 255))
assert_equal(table(ImageChops.logical_xor, 0, 1), (0, 255, 255, 0))
assert_equal(table(ImageChops.logical_and, 0, 128), (0, 0, 0, 255)) def table(op, a, b):
assert_equal(table(ImageChops.logical_or, 0, 128), (0, 255, 255, 255)) out = []
assert_equal(table(ImageChops.logical_xor, 0, 128), (0, 255, 255, 0)) for x in (a, b):
imx = Image.new("1", (1, 1), x)
for y in (a, b):
imy = Image.new("1", (1, 1), y)
out.append(op(imx, imy).getpixel((0, 0)))
return tuple(out)
assert_equal(table(ImageChops.logical_and, 0, 255), (0, 0, 0, 255)) self.assertEqual(
assert_equal(table(ImageChops.logical_or, 0, 255), (0, 255, 255, 255)) table(ImageChops.logical_and, 0, 1), (0, 0, 0, 255))
assert_equal(table(ImageChops.logical_xor, 0, 255), (0, 255, 255, 0)) self.assertEqual(
table(ImageChops.logical_or, 0, 1), (0, 255, 255, 255))
self.assertEqual(
table(ImageChops.logical_xor, 0, 1), (0, 255, 255, 0))
self.assertEqual(
table(ImageChops.logical_and, 0, 128), (0, 0, 0, 255))
self.assertEqual(
table(ImageChops.logical_or, 0, 128), (0, 255, 255, 255))
self.assertEqual(
table(ImageChops.logical_xor, 0, 128), (0, 255, 255, 0))
self.assertEqual(
table(ImageChops.logical_and, 0, 255), (0, 0, 0, 255))
self.assertEqual(
table(ImageChops.logical_or, 0, 255), (0, 255, 255, 255))
self.assertEqual(
table(ImageChops.logical_xor, 0, 255), (0, 255, 255, 0))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,203 +1,214 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
try: try:
from PIL import ImageCms from PIL import ImageCms
ImageCms.core.profile_open ImageCms.core.profile_open
except ImportError: except ImportError as v:
skip() # Skipped via setUp()
pass
SRGB = "Tests/icc/sRGB.icm" SRGB = "Tests/icc/sRGB.icm"
def test_sanity(): class TestImageCms(PillowTestCase):
# basic smoke test. def setUp(self):
# this mostly follows the cms_test outline. try:
from PIL import ImageCms
except ImportError as v:
self.skipTest(v)
v = ImageCms.versions() # should return four strings def test_sanity(self):
assert_equal(v[0], '1.0.0 pil')
assert_equal(list(map(type, v)), [str, str, str, str])
# internal version number # basic smoke test.
assert_match(ImageCms.core.littlecms_version, "\d+\.\d+$") # this mostly follows the cms_test outline.
i = ImageCms.profileToProfile(lena(), SRGB, SRGB) v = ImageCms.versions() # should return four strings
assert_image(i, "RGB", (128, 128)) self.assertEqual(v[0], '1.0.0 pil')
self.assertEqual(list(map(type, v)), [str, str, str, str])
i = lena() # internal version number
ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True) self.assertRegexpMatches(ImageCms.core.littlecms_version, "\d+\.\d+$")
assert_image(i, "RGB", (128, 128))
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB") i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
i = ImageCms.applyTransform(lena(), t) self.assert_image(i, "RGB", (128, 128))
assert_image(i, "RGB", (128, 128))
i = lena() i = lena()
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB") ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
ImageCms.applyTransform(lena(), t, inPlace=True) self.assert_image(i, "RGB", (128, 128))
assert_image(i, "RGB", (128, 128))
p = ImageCms.createProfile("sRGB") t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
o = ImageCms.getOpenProfile(SRGB) i = ImageCms.applyTransform(lena(), t)
t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB") self.assert_image(i, "RGB", (128, 128))
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "RGB", (128, 128))
t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB") i = lena()
assert_equal(t.inputMode, "RGB") t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
assert_equal(t.outputMode, "RGB") ImageCms.applyTransform(lena(), t, inPlace=True)
i = ImageCms.applyTransform(lena(), t) self.assert_image(i, "RGB", (128, 128))
assert_image(i, "RGB", (128, 128))
# test PointTransform convenience API p = ImageCms.createProfile("sRGB")
lena().point(t) o = ImageCms.getOpenProfile(SRGB)
t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
self.assertEqual(t.inputMode, "RGB")
self.assertEqual(t.outputMode, "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
# test PointTransform convenience API
lena().point(t)
def test_name(self):
# get profile information for file
self.assertEqual(
ImageCms.getProfileName(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_info(self):
self.assertEqual(
ImageCms.getProfileInfo(SRGB).splitlines(), [
'sRGB IEC61966-2.1', '',
'Copyright (c) 1998 Hewlett-Packard Company', ''])
def test_copyright(self):
self.assertEqual(
ImageCms.getProfileCopyright(SRGB).strip(),
'Copyright (c) 1998 Hewlett-Packard Company')
def test_manufacturer(self):
self.assertEqual(
ImageCms.getProfileManufacturer(SRGB).strip(),
'IEC http://www.iec.ch')
def test_model(self):
self.assertEqual(
ImageCms.getProfileModel(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_description(self):
self.assertEqual(
ImageCms.getProfileDescription(SRGB).strip(),
'sRGB IEC61966-2.1')
def test_intent(self):
self.assertEqual(ImageCms.getDefaultIntent(SRGB), 0)
self.assertEqual(ImageCms.isIntentSupported(
SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_profile_object(self):
# same, using profile object
p = ImageCms.createProfile("sRGB")
# self.assertEqual(ImageCms.getProfileName(p).strip(),
# 'sRGB built-in - (lcms internal)')
# self.assertEqual(ImageCms.getProfileInfo(p).splitlines(),
# ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
self.assertEqual(ImageCms.getDefaultIntent(p), 0)
self.assertEqual(ImageCms.isIntentSupported(
p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_extensions(self):
# extensions
from io import BytesIO
i = Image.open("Tests/images/rgb.jpg")
p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
self.assertEqual(
ImageCms.getProfileName(p).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_exceptions(self):
# the procedural pyCMS API uses PyCMSError for all sorts of errors
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.getProfileName(None))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.isIntentSupported(SRGB, None, None))
def test_display_profile(self):
# try fetching the profile for the current display device
ImageCms.get_display_profile()
def test_lab_color_profile(self):
ImageCms.createProfile("LAB", 5000)
ImageCms.createProfile("LAB", 6500)
def test_simple_lab(self):
i = Image.new('RGB', (10, 10), (128, 128, 128))
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
i_lab = ImageCms.applyTransform(i, t)
self.assertEqual(i_lab.mode, 'LAB')
k = i_lab.getpixel((0, 0))
# not a linear luminance map. so L != 128:
self.assertEqual(k, (137, 128, 128))
L = i_lab.getdata(0)
a = i_lab.getdata(1)
b = i_lab.getdata(2)
self.assertEqual(list(L), [137] * 100)
self.assertEqual(list(a), [128] * 100)
self.assertEqual(list(b), [128] * 100)
def test_lab_color(self):
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
# Need to add a type mapping for some PIL type to TYPE_Lab_8 in
# findLCMSType, and have that mapping work back to a PIL mode
# (likely RGB).
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "LAB", (128, 128))
# i.save('temp.lab.tif') # visually verified vs PS.
target = Image.open('Tests/images/lena.Lab.tif')
self.assert_image_similar(i, target, 30)
def test_lab_srgb(self):
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
img = Image.open('Tests/images/lena.Lab.tif')
img_srgb = ImageCms.applyTransform(img, t)
# img_srgb.save('temp.srgb.tif') # visually verified vs ps.
self.assert_image_similar(lena(), img_srgb, 30)
def test_lab_roundtrip(self):
# check to see if we're at least internally consistent.
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
t2 = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
i = ImageCms.applyTransform(lena(), t)
out = ImageCms.applyTransform(i, t2)
self.assert_image_similar(lena(), out, 2)
def test_name(): if __name__ == '__main__':
# get profile information for file unittest.main()
assert_equal(ImageCms.getProfileName(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
# End of file
def test_info():
assert_equal(ImageCms.getProfileInfo(SRGB).splitlines(),
['sRGB IEC61966-2.1', '',
'Copyright (c) 1998 Hewlett-Packard Company', ''])
def test_copyright():
assert_equal(ImageCms.getProfileCopyright(SRGB).strip(),
'Copyright (c) 1998 Hewlett-Packard Company')
def test_manufacturer():
assert_equal(ImageCms.getProfileManufacturer(SRGB).strip(),
'IEC http://www.iec.ch')
def test_model():
assert_equal(ImageCms.getProfileModel(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_description():
assert_equal(ImageCms.getProfileDescription(SRGB).strip(),
'sRGB IEC61966-2.1')
def test_intent():
assert_equal(ImageCms.getDefaultIntent(SRGB), 0)
assert_equal(ImageCms.isIntentSupported(
SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_profile_object():
# same, using profile object
p = ImageCms.createProfile("sRGB")
# assert_equal(ImageCms.getProfileName(p).strip(),
# 'sRGB built-in - (lcms internal)')
# assert_equal(ImageCms.getProfileInfo(p).splitlines(),
# ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
assert_equal(ImageCms.getDefaultIntent(p), 0)
assert_equal(ImageCms.isIntentSupported(
p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_extensions():
# extensions
i = Image.open("Tests/images/rgb.jpg")
p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
assert_equal(ImageCms.getProfileName(p).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_exceptions():
# the procedural pyCMS API uses PyCMSError for all sorts of errors
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.getProfileName(None))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.isIntentSupported(SRGB, None, None))
def test_display_profile():
# try fetching the profile for the current display device
assert_no_exception(lambda: ImageCms.get_display_profile())
def test_lab_color_profile():
ImageCms.createProfile("LAB", 5000)
ImageCms.createProfile("LAB", 6500)
def test_simple_lab():
i = Image.new('RGB', (10, 10), (128, 128, 128))
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
i_lab = ImageCms.applyTransform(i, t)
assert_equal(i_lab.mode, 'LAB')
k = i_lab.getpixel((0, 0))
assert_equal(k, (137, 128, 128)) # not a linear luminance map. so L != 128
L = i_lab.getdata(0)
a = i_lab.getdata(1)
b = i_lab.getdata(2)
assert_equal(list(L), [137] * 100)
assert_equal(list(a), [128] * 100)
assert_equal(list(b), [128] * 100)
def test_lab_color():
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
# Need to add a type mapping for some PIL type to TYPE_Lab_8 in
# findLCMSType, and have that mapping work back to a PIL mode (likely RGB).
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "LAB", (128, 128))
# i.save('temp.lab.tif') # visually verified vs PS.
target = Image.open('Tests/images/lena.Lab.tif')
assert_image_similar(i, target, 30)
def test_lab_srgb():
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
img = Image.open('Tests/images/lena.Lab.tif')
img_srgb = ImageCms.applyTransform(img, t)
# img_srgb.save('temp.srgb.tif') # visually verified vs ps.
assert_image_similar(lena(), img_srgb, 30)
def test_lab_roundtrip():
# check to see if we're at least internally consistent.
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
t2 = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
i = ImageCms.applyTransform(lena(), t)
out = ImageCms.applyTransform(i, t2)
assert_image_similar(lena(), out, 2)

View File

@ -1,54 +1,71 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
from PIL import ImageColor from PIL import ImageColor
# --------------------------------------------------------------------
# sanity
assert_equal((255, 0, 0), ImageColor.getrgb("#f00")) class TestImageColor(PillowTestCase):
assert_equal((255, 0, 0), ImageColor.getrgb("#ff0000"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(255, 0, 0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
assert_equal((255, 0, 0), ImageColor.getrgb("hsl(0, 100%, 50%)"))
assert_equal((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
assert_equal((255, 0, 0, 0), ImageColor.getrgb("rgba(255, 0, 0, 0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("red"))
# -------------------------------------------------------------------- def test_sanity(self):
# look for rounding errors (based on code by Tim Hatch) self.assertEqual((255, 0, 0), ImageColor.getrgb("#f00"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("#ff0000"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255, 0, 0)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(0, 100%, 50%)"))
self.assertEqual((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
self.assertEqual(
(255, 0, 0, 0), ImageColor.getrgb("rgba(255, 0, 0, 0)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("red"))
for color in list(ImageColor.colormap.keys()): # look for rounding errors (based on code by Tim Hatch)
expected = Image.new("RGB", (1, 1), color).convert("L").getpixel((0, 0)) def test_rounding_errors(self):
actual = Image.new("L", (1, 1), color).getpixel((0, 0))
assert_equal(expected, actual)
assert_equal((0, 0, 0), ImageColor.getcolor("black", "RGB")) for color in list(ImageColor.colormap.keys()):
assert_equal((255, 255, 255), ImageColor.getcolor("white", "RGB")) expected = Image.new(
assert_equal((0, 255, 115), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGB")) "RGB", (1, 1), color).convert("L").getpixel((0, 0))
Image.new("RGB", (1, 1), "white") actual = Image.new("L", (1, 1), color).getpixel((0, 0))
self.assertEqual(expected, actual)
assert_equal((0, 0, 0, 255), ImageColor.getcolor("black", "RGBA")) self.assertEqual((0, 0, 0), ImageColor.getcolor("black", "RGB"))
assert_equal((255, 255, 255, 255), ImageColor.getcolor("white", "RGBA")) self.assertEqual((255, 255, 255), ImageColor.getcolor("white", "RGB"))
assert_equal((0, 255, 115, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGBA")) self.assertEqual(
Image.new("RGBA", (1, 1), "white") (0, 255, 115), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGB"))
Image.new("RGB", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "L")) self.assertEqual((0, 0, 0, 255), ImageColor.getcolor("black", "RGBA"))
assert_equal(255, ImageColor.getcolor("white", "L")) self.assertEqual(
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "L")) (255, 255, 255, 255), ImageColor.getcolor("white", "RGBA"))
Image.new("L", (1, 1), "white") self.assertEqual(
(0, 255, 115, 33),
ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGBA"))
Image.new("RGBA", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "1")) self.assertEqual(0, ImageColor.getcolor("black", "L"))
assert_equal(255, ImageColor.getcolor("white", "1")) self.assertEqual(255, ImageColor.getcolor("white", "L"))
# The following test is wrong, but is current behavior self.assertEqual(
# The correct result should be 255 due to the mode 1 162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "L"))
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1")) Image.new("L", (1, 1), "white")
# Correct behavior
# assert_equal(255, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
Image.new("1", (1, 1), "white")
assert_equal((0, 255), ImageColor.getcolor("black", "LA")) self.assertEqual(0, ImageColor.getcolor("black", "1"))
assert_equal((255, 255), ImageColor.getcolor("white", "LA")) self.assertEqual(255, ImageColor.getcolor("white", "1"))
assert_equal((162, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA")) # The following test is wrong, but is current behavior
Image.new("LA", (1, 1), "white") # The correct result should be 255 due to the mode 1
self.assertEqual(
162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
# Correct behavior
# self.assertEqual(
# 255, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
Image.new("1", (1, 1), "white")
self.assertEqual((0, 255), ImageColor.getcolor("black", "LA"))
self.assertEqual((255, 255), ImageColor.getcolor("white", "LA"))
self.assertEqual(
(162, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA"))
Image.new("LA", (1, 1), "white")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,9 +1,11 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
from PIL import ImageColor from PIL import ImageColor
from PIL import ImageDraw from PIL import ImageDraw
import sys
# Image size # Image size
w, h = 100, 100 w, h = 100, 100
@ -22,249 +24,232 @@ points1 = [(10, 10), (20, 40), (30, 30)]
points2 = [10, 10, 20, 40, 30, 30] points2 = [10, 10, 20, 40, 30, 30]
def test_sanity(): class TestImageDraw(PillowTestCase):
im = lena("RGB").copy() def test_sanity(self):
im = lena("RGB").copy()
draw = ImageDraw.ImageDraw(im) draw = ImageDraw.ImageDraw(im)
draw = ImageDraw.Draw(im) draw = ImageDraw.Draw(im)
draw.ellipse(list(range(4))) draw.ellipse(list(range(4)))
draw.line(list(range(10))) draw.line(list(range(10)))
draw.polygon(list(range(100))) draw.polygon(list(range(100)))
draw.rectangle(list(range(4))) draw.rectangle(list(range(4)))
success() def test_deprecated(self):
im = lena().copy()
draw = ImageDraw.Draw(im)
def test_deprecated(): self.assert_warning(DeprecationWarning, lambda: draw.setink(0))
self.assert_warning(DeprecationWarning, lambda: draw.setfill(0))
im = lena().copy() def helper_arc(self, bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
draw = ImageDraw.Draw(im) # Act
# FIXME Fill param should be named outline.
draw.arc(bbox, 0, 180)
del draw
assert_warning(DeprecationWarning, lambda: draw.setink(0)) # Assert
assert_warning(DeprecationWarning, lambda: draw.setfill(0)) self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_arc.png"))
def test_arc1(self):
self.helper_arc(bbox1)
def helper_arc(bbox): def test_arc2(self):
# Arrange self.helper_arc(bbox2)
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act def test_bitmap(self):
# FIXME Fill param should be named outline. # Arrange
draw.arc(bbox, 0, 180) small = Image.open("Tests/images/pil123rgba.png").resize((50, 50))
del draw im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Assert # Act
assert_image_equal(im, Image.open("Tests/images/imagedraw_arc.png")) draw.bitmap((10, 10), small)
del draw
# Assert
self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_bitmap.png"))
def test_arc1(): def helper_chord(self, bbox):
helper_arc(bbox1) # Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.chord(bbox, 0, 180, fill="red", outline="yellow")
del draw
def test_arc2(): # Assert
helper_arc(bbox2) self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_chord.png"))
def test_chord1(self):
self.helper_chord(bbox1)
def test_bitmap(): def test_chord2(self):
# Arrange self.helper_chord(bbox2)
small = Image.open("Tests/images/pil123rgba.png").resize((50, 50))
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act def helper_ellipse(self, bbox):
draw.bitmap((10, 10), small) # Arrange
del draw im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Assert # Act
assert_image_equal(im, Image.open("Tests/images/imagedraw_bitmap.png")) draw.ellipse(bbox, fill="green", outline="blue")
del draw
# Assert
self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_ellipse.png"))
def helper_chord(bbox): def test_ellipse1(self):
# Arrange self.helper_ellipse(bbox1)
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act def test_ellipse2(self):
draw.chord(bbox, 0, 180, fill="red", outline="yellow") self.helper_ellipse(bbox2)
del draw
# Assert def helper_line(self, points):
assert_image_equal(im, Image.open("Tests/images/imagedraw_chord.png")) # Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.line(points1, fill="yellow", width=2)
del draw
def test_chord1(): # Assert
helper_chord(bbox1) self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_line.png"))
def test_line1(self):
self.helper_line(points1)
def test_chord2(): def test_line2(self):
helper_chord(bbox2) self.helper_line(points2)
def helper_pieslice(self, bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
def helper_ellipse(bbox): # Act
# Arrange draw.pieslice(bbox, -90, 45, fill="white", outline="blue")
im = Image.new("RGB", (w, h)) del draw
draw = ImageDraw.Draw(im)
# Act # Assert
draw.ellipse(bbox, fill="green", outline="blue") self.assert_image_equal(
del draw im, Image.open("Tests/images/imagedraw_pieslice.png"))
# Assert def test_pieslice1(self):
assert_image_equal(im, Image.open("Tests/images/imagedraw_ellipse.png")) self.helper_pieslice(bbox1)
def test_pieslice2(self):
self.helper_pieslice(bbox2)
def test_ellipse1(): def helper_point(self, points):
helper_ellipse(bbox1) # Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.point(points1, fill="yellow")
del draw
def test_ellipse2(): # Assert
helper_ellipse(bbox2) self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_point.png"))
def test_point1(self):
self.helper_point(points1)
def helper_line(points): def test_point2(self):
# Arrange self.helper_point(points2)
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act def helper_polygon(self, points):
draw.line(points1, fill="yellow", width=2) # Arrange
del draw im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Assert # Act
assert_image_equal(im, Image.open("Tests/images/imagedraw_line.png")) draw.polygon(points1, fill="red", outline="blue")
del draw
# Assert
self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_polygon.png"))
def test_line1(): def test_polygon1(self):
helper_line(points1) self.helper_polygon(points1)
def test_polygon2(self):
self.helper_polygon(points2)
def test_line2(): def helper_rectangle(self, bbox):
helper_line(points2) # Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.rectangle(bbox, fill="black", outline="green")
del draw
def helper_pieslice(bbox): # Assert
# Arrange self.assert_image_equal(
im = Image.new("RGB", (w, h)) im, Image.open("Tests/images/imagedraw_rectangle.png"))
draw = ImageDraw.Draw(im)
# Act def test_rectangle1(self):
draw.pieslice(bbox, -90, 45, fill="white", outline="blue") self.helper_rectangle(bbox1)
del draw
# Assert def test_rectangle2(self):
assert_image_equal(im, Image.open("Tests/images/imagedraw_pieslice.png")) self.helper_rectangle(bbox2)
def test_floodfill(self):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
draw.rectangle(bbox2, outline="yellow", fill="green")
centre_point = (int(w/2), int(h/2))
def test_pieslice1(): # Act
helper_pieslice(bbox1) ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red"))
del draw
# Assert
self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_floodfill.png"))
def test_pieslice2(): @unittest.skipIf(hasattr(sys, 'pypy_version_info'),
helper_pieslice(bbox2) "Causes fatal RPython error on PyPy")
def test_floodfill_border(self):
# floodfill() is experimental
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
draw.rectangle(bbox2, outline="yellow", fill="green")
centre_point = (int(w/2), int(h/2))
def helper_point(points): # Act
# Arrange ImageDraw.floodfill(
im = Image.new("RGB", (w, h)) im, centre_point, ImageColor.getrgb("red"),
draw = ImageDraw.Draw(im) border=ImageColor.getrgb("black"))
del draw
# Act # Assert
draw.point(points1, fill="yellow") self.assert_image_equal(
del draw im, Image.open("Tests/images/imagedraw_floodfill2.png"))
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_point.png"))
def test_point1():
helper_point(points1)
def test_point2():
helper_point(points2)
def helper_polygon(points):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.polygon(points1, fill="red", outline="blue")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_polygon.png"))
def test_polygon1():
helper_polygon(points1)
def test_polygon2():
helper_polygon(points2)
def helper_rectangle(bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.rectangle(bbox, fill="black", outline="green")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_rectangle.png"))
def test_rectangle1():
helper_rectangle(bbox1)
def test_rectangle2():
helper_rectangle(bbox2)
def test_floodfill():
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
draw.rectangle(bbox2, outline="yellow", fill="green")
centre_point = (int(w/2), int(h/2))
# Act
ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red"))
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill.png"))
def test_floodfill_border():
# floodfill() is experimental
if hasattr(sys, 'pypy_version_info'):
# Causes fatal RPython error on PyPy
skip()
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
draw.rectangle(bbox2, outline="yellow", fill="green")
centre_point = (int(w/2), int(h/2))
# Act
ImageDraw.floodfill(
im, centre_point, ImageColor.getrgb("red"),
border=ImageColor.getrgb("black"))
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
if __name__ == '__main__':
unittest.main()
# End of file # End of file

View File

@ -1,19 +1,28 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
from PIL import ImageEnhance from PIL import ImageEnhance
def test_sanity():
# FIXME: assert_image class TestImageEnhance(PillowTestCase):
assert_no_exception(lambda: ImageEnhance.Color(lena()).enhance(0.5))
assert_no_exception(lambda: ImageEnhance.Contrast(lena()).enhance(0.5))
assert_no_exception(lambda: ImageEnhance.Brightness(lena()).enhance(0.5))
assert_no_exception(lambda: ImageEnhance.Sharpness(lena()).enhance(0.5))
def test_crash(): def test_sanity(self):
# crashes on small images # FIXME: assert_image
im = Image.new("RGB", (1, 1)) # Implicit asserts no exception:
assert_no_exception(lambda: ImageEnhance.Sharpness(im).enhance(0.5)) ImageEnhance.Color(lena()).enhance(0.5)
ImageEnhance.Contrast(lena()).enhance(0.5)
ImageEnhance.Brightness(lena()).enhance(0.5)
ImageEnhance.Sharpness(lena()).enhance(0.5)
def test_crash(self):
# crashes on small images
im = Image.new("RGB", (1, 1))
ImageEnhance.Sharpness(im).enhance(0.5)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,82 +1,93 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena, fromstring, tostring
from io import BytesIO
from PIL import Image from PIL import Image
from PIL import ImageFile from PIL import ImageFile
from PIL import EpsImagePlugin from PIL import EpsImagePlugin
codecs = dir(Image.core) codecs = dir(Image.core)
# save original block sizes # save original block sizes
MAXBLOCK = ImageFile.MAXBLOCK MAXBLOCK = ImageFile.MAXBLOCK
SAFEBLOCK = ImageFile.SAFEBLOCK SAFEBLOCK = ImageFile.SAFEBLOCK
def test_parser():
def roundtrip(format): class TestImagePutData(PillowTestCase):
im = lena("L").resize((1000, 1000)) def test_parser(self):
if format in ("MSP", "XBM"):
im = im.convert("1")
file = BytesIO() def roundtrip(format):
im.save(file, format) im = lena("L").resize((1000, 1000))
if format in ("MSP", "XBM"):
im = im.convert("1")
data = file.getvalue() file = BytesIO()
parser = ImageFile.Parser() im.save(file, format)
parser.feed(data)
imOut = parser.close()
return im, imOut data = file.getvalue()
parser = ImageFile.Parser()
parser.feed(data)
imOut = parser.close()
return im, imOut
self.assert_image_equal(*roundtrip("BMP"))
self.assert_image_equal(*roundtrip("GIF"))
self.assert_image_equal(*roundtrip("IM"))
self.assert_image_equal(*roundtrip("MSP"))
if "zip_encoder" in codecs:
try:
# force multiple blocks in PNG driver
ImageFile.MAXBLOCK = 8192
self.assert_image_equal(*roundtrip("PNG"))
finally:
ImageFile.MAXBLOCK = MAXBLOCK
self.assert_image_equal(*roundtrip("PPM"))
self.assert_image_equal(*roundtrip("TIFF"))
self.assert_image_equal(*roundtrip("XBM"))
self.assert_image_equal(*roundtrip("TGA"))
self.assert_image_equal(*roundtrip("PCX"))
if EpsImagePlugin.has_ghostscript():
im1, im2 = roundtrip("EPS")
# EPS comes back in RGB:
self.assert_image_similar(im1, im2.convert('L'), 20)
if "jpeg_encoder" in codecs:
im1, im2 = roundtrip("JPEG") # lossy compression
self.assert_image(im1, im2.mode, im2.size)
self.assertRaises(IOError, lambda: roundtrip("PDF"))
def test_ico(self):
with open('Tests/images/python.ico', 'rb') as f:
data = f.read()
p = ImageFile.Parser()
p.feed(data)
self.assertEqual((48, 48), p.image.size)
def test_safeblock(self):
im1 = lena()
if "zip_encoder" not in codecs:
self.skipTest("PNG (zlib) encoder not available")
assert_image_equal(*roundtrip("BMP"))
assert_image_equal(*roundtrip("GIF"))
assert_image_equal(*roundtrip("IM"))
assert_image_equal(*roundtrip("MSP"))
if "zip_encoder" in codecs:
try: try:
# force multiple blocks in PNG driver ImageFile.SAFEBLOCK = 1
ImageFile.MAXBLOCK = 8192 im2 = fromstring(tostring(im1, "PNG"))
assert_image_equal(*roundtrip("PNG"))
finally: finally:
ImageFile.MAXBLOCK = MAXBLOCK ImageFile.SAFEBLOCK = SAFEBLOCK
assert_image_equal(*roundtrip("PPM"))
assert_image_equal(*roundtrip("TIFF"))
assert_image_equal(*roundtrip("XBM"))
assert_image_equal(*roundtrip("TGA"))
assert_image_equal(*roundtrip("PCX"))
if EpsImagePlugin.has_ghostscript(): self.assert_image_equal(im1, im2)
im1, im2 = roundtrip("EPS")
assert_image_similar(im1, im2.convert('L'),20) # EPS comes back in RGB
if "jpeg_encoder" in codecs:
im1, im2 = roundtrip("JPEG") # lossy compression
assert_image(im1, im2.mode, im2.size)
# XXX Why assert exception and why does it fail? if __name__ == '__main__':
# https://github.com/python-pillow/Pillow/issues/78 unittest.main()
#assert_exception(IOError, lambda: roundtrip("PDF"))
def test_ico(): # End of file
with open('Tests/images/python.ico', 'rb') as f:
data = f.read()
p = ImageFile.Parser()
p.feed(data)
assert_equal((48,48), p.image.size)
def test_safeblock():
im1 = lena()
if "zip_encoder" not in codecs:
skip("PNG (zlib) encoder not available")
try:
ImageFile.SAFEBLOCK = 1
im2 = fromstring(tostring(im1, "PNG"))
finally:
ImageFile.SAFEBLOCK = SAFEBLOCK
assert_image_equal(im1, im2)

View File

@ -1,24 +1,33 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena, tostring
from PIL import Image from PIL import Image
from PIL import ImageFileIO from PIL import ImageFileIO
def test_fileio():
class DumbFile: class TestImageFileIo(PillowTestCase):
def __init__(self, data):
self.data = data
def read(self, bytes=None):
assert_equal(bytes, None)
return self.data
def close(self):
pass
im1 = lena() def test_fileio(self):
io = ImageFileIO.ImageFileIO(DumbFile(tostring(im1, "PPM"))) class DumbFile:
def __init__(self, data):
self.data = data
im2 = Image.open(io) def read(self, bytes=None):
assert_image_equal(im1, im2) assert(bytes is None)
return self.data
def close(self):
pass
im1 = lena()
io = ImageFileIO.ImageFileIO(DumbFile(tostring(im1, "PPM")))
im2 = Image.open(io)
self.assert_image_equal(im1, im2)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,31 +1,37 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image
from PIL import ImageFilter from PIL import ImageFilter
def test_sanity():
# see test_image_filter for more tests
assert_no_exception(lambda: ImageFilter.MaxFilter) class TestImageFilter(PillowTestCase):
assert_no_exception(lambda: ImageFilter.MedianFilter)
assert_no_exception(lambda: ImageFilter.MinFilter)
assert_no_exception(lambda: ImageFilter.ModeFilter)
assert_no_exception(lambda: ImageFilter.Kernel((3, 3), list(range(9))))
assert_no_exception(lambda: ImageFilter.GaussianBlur)
assert_no_exception(lambda: ImageFilter.GaussianBlur(5))
assert_no_exception(lambda: ImageFilter.UnsharpMask)
assert_no_exception(lambda: ImageFilter.UnsharpMask(10))
assert_no_exception(lambda: ImageFilter.BLUR) def test_sanity(self):
assert_no_exception(lambda: ImageFilter.CONTOUR) # see test_image_filter for more tests
assert_no_exception(lambda: ImageFilter.DETAIL)
assert_no_exception(lambda: ImageFilter.EDGE_ENHANCE) # Check these run. Exceptions cause failures.
assert_no_exception(lambda: ImageFilter.EDGE_ENHANCE_MORE) ImageFilter.MaxFilter
assert_no_exception(lambda: ImageFilter.EMBOSS) ImageFilter.MedianFilter
assert_no_exception(lambda: ImageFilter.FIND_EDGES) ImageFilter.MinFilter
assert_no_exception(lambda: ImageFilter.SMOOTH) ImageFilter.ModeFilter
assert_no_exception(lambda: ImageFilter.SMOOTH_MORE) ImageFilter.Kernel((3, 3), list(range(9)))
assert_no_exception(lambda: ImageFilter.SHARPEN) ImageFilter.GaussianBlur
ImageFilter.GaussianBlur(5)
ImageFilter.UnsharpMask
ImageFilter.UnsharpMask(10)
ImageFilter.BLUR
ImageFilter.CONTOUR
ImageFilter.DETAIL
ImageFilter.EDGE_ENHANCE
ImageFilter.EDGE_ENHANCE_MORE
ImageFilter.EMBOSS
ImageFilter.FIND_EDGES
ImageFilter.SMOOTH
ImageFilter.SMOOTH_MORE
ImageFilter.SHARPEN
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,135 +1,145 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
from PIL import ImageDraw
from io import BytesIO from io import BytesIO
import os import os
font_path = "Tests/fonts/FreeMono.ttf"
font_size = 20
try: try:
from PIL import ImageFont from PIL import ImageFont
ImageFont.core.getfont # check if freetype is available ImageFont.core.getfont # check if freetype is available
class TestImageFont(PillowTestCase):
def test_sanity(self):
self.assertRegexpMatches(
ImageFont.core.freetype2_version, "\d+\.\d+\.\d+$")
def test_font_with_name(self):
ImageFont.truetype(font_path, font_size)
self._render(font_path)
self._clean()
def _font_as_bytes(self):
with open(font_path, 'rb') as f:
font_bytes = BytesIO(f.read())
return font_bytes
def test_font_with_filelike(self):
ImageFont.truetype(self._font_as_bytes(), font_size)
self._render(self._font_as_bytes())
# Usage note: making two fonts from the same buffer fails.
# shared_bytes = self._font_as_bytes()
# self._render(shared_bytes)
# self.assertRaises(Exception, lambda: _render(shared_bytes))
self._clean()
def test_font_with_open_file(self):
with open(font_path, 'rb') as f:
self._render(f)
self._clean()
def test_font_old_parameters(self):
self.assert_warning(
DeprecationWarning,
lambda: ImageFont.truetype(filename=font_path, size=font_size))
def _render(self, font):
txt = "Hello World!"
ttf = ImageFont.truetype(font, font_size)
w, h = ttf.getsize(txt)
img = Image.new("RGB", (256, 64), "white")
d = ImageDraw.Draw(img)
d.text((10, 10), txt, font=ttf, fill='black')
img.save('font.png')
return img
def _clean(self):
os.unlink('font.png')
def test_render_equal(self):
img_path = self._render(font_path)
with open(font_path, 'rb') as f:
font_filelike = BytesIO(f.read())
img_filelike = self._render(font_filelike)
self.assert_image_equal(img_path, img_filelike)
self._clean()
def test_render_multiline(self):
im = Image.new(mode='RGB', size=(300, 100))
draw = ImageDraw.Draw(im)
ttf = ImageFont.truetype(font_path, font_size)
line_spacing = draw.textsize('A', font=ttf)[1] + 8
lines = ['hey you', 'you are awesome', 'this looks awkward']
y = 0
for line in lines:
draw.text((0, y), line, font=ttf)
y += line_spacing
target = 'Tests/images/multiline_text.png'
target_img = Image.open(target)
# some versions of freetype have different horizontal spacing.
# setting a tight epsilon, I'm showing the original test failure
# at epsilon = ~38.
self.assert_image_similar(im, target_img, .5)
def test_rotated_transposed_font(self):
img_grey = Image.new("L", (100, 100))
draw = ImageDraw.Draw(img_grey)
word = "testing"
font = ImageFont.truetype(font_path, font_size)
orientation = Image.ROTATE_90
transposed_font = ImageFont.TransposedFont(
font, orientation=orientation)
# Original font
draw.setfont(font)
box_size_a = draw.textsize(word)
# Rotated font
draw.setfont(transposed_font)
box_size_b = draw.textsize(word)
# Check (w,h) of box a is (h,w) of box b
self.assertEqual(box_size_a[0], box_size_b[1])
self.assertEqual(box_size_a[1], box_size_b[0])
def test_unrotated_transposed_font(self):
img_grey = Image.new("L", (100, 100))
draw = ImageDraw.Draw(img_grey)
word = "testing"
font = ImageFont.truetype(font_path, font_size)
orientation = None
transposed_font = ImageFont.TransposedFont(
font, orientation=orientation)
# Original font
draw.setfont(font)
box_size_a = draw.textsize(word)
# Rotated font
draw.setfont(transposed_font)
box_size_b = draw.textsize(word)
# Check boxes a and b are same size
self.assertEqual(box_size_a, box_size_b)
except ImportError: except ImportError:
skip() class TestImageFont(PillowTestCase):
def test_skip(self):
from PIL import ImageDraw self.skipTest("ImportError")
font_path = "Tests/fonts/FreeMono.ttf"
font_size=20
def test_sanity():
assert_match(ImageFont.core.freetype2_version, "\d+\.\d+\.\d+$")
def test_font_with_name():
assert_no_exception(lambda: ImageFont.truetype(font_path, font_size))
assert_no_exception(lambda: _render(font_path))
_clean()
def _font_as_bytes():
with open(font_path, 'rb') as f:
font_bytes = BytesIO(f.read())
return font_bytes
def test_font_with_filelike():
assert_no_exception(lambda: ImageFont.truetype(_font_as_bytes(), font_size))
assert_no_exception(lambda: _render(_font_as_bytes()))
# Usage note: making two fonts from the same buffer fails.
#shared_bytes = _font_as_bytes()
#assert_no_exception(lambda: _render(shared_bytes))
#assert_exception(Exception, lambda: _render(shared_bytes))
_clean()
def test_font_with_open_file():
with open(font_path, 'rb') as f:
assert_no_exception(lambda: _render(f))
_clean()
def test_font_old_parameters():
assert_warning(DeprecationWarning, lambda: ImageFont.truetype(filename=font_path, size=font_size))
def _render(font):
txt = "Hello World!"
ttf = ImageFont.truetype(font, font_size)
w, h = ttf.getsize(txt)
img = Image.new("RGB", (256, 64), "white")
d = ImageDraw.Draw(img)
d.text((10, 10), txt, font=ttf, fill='black')
img.save('font.png')
return img
def _clean():
os.unlink('font.png')
def test_render_equal():
img_path = _render(font_path)
with open(font_path, 'rb') as f:
font_filelike = BytesIO(f.read())
img_filelike = _render(font_filelike)
assert_image_equal(img_path, img_filelike)
_clean()
def test_render_multiline(): if __name__ == '__main__':
im = Image.new(mode='RGB', size=(300,100)) unittest.main()
draw = ImageDraw.Draw(im)
ttf = ImageFont.truetype(font_path, font_size)
line_spacing = draw.textsize('A', font=ttf)[1] + 8
lines = ['hey you', 'you are awesome', 'this looks awkward']
y = 0
for line in lines:
draw.text((0, y), line, font=ttf)
y += line_spacing
target = 'Tests/images/multiline_text.png'
target_img = Image.open(target)
# some versions of freetype have different horizontal spacing.
# setting a tight epsilon, I'm showing the original test failure
# at epsilon = ~38.
assert_image_similar(im, target_img,.5)
def test_rotated_transposed_font():
img_grey = Image.new("L", (100, 100))
draw = ImageDraw.Draw(img_grey)
word = "testing"
font = ImageFont.truetype(font_path, font_size)
orientation = Image.ROTATE_90
transposed_font = ImageFont.TransposedFont(font, orientation=orientation)
# Original font
draw.setfont(font)
box_size_a = draw.textsize(word)
# Rotated font
draw.setfont(transposed_font)
box_size_b = draw.textsize(word)
# Check (w,h) of box a is (h,w) of box b
assert_equal(box_size_a[0], box_size_b[1])
assert_equal(box_size_a[1], box_size_b[0])
def test_unrotated_transposed_font():
img_grey = Image.new("L", (100, 100))
draw = ImageDraw.Draw(img_grey)
word = "testing"
font = ImageFont.truetype(font_path, font_size)
orientation = None
transposed_font = ImageFont.TransposedFont(font, orientation=orientation)
# Original font
draw.setfont(font)
box_size_a = draw.textsize(word)
# Rotated font
draw.setfont(transposed_font)
box_size_b = draw.textsize(word)
# Check boxes a and b are same size
assert_equal(box_size_a, box_size_b)
# End of file

View File

@ -1,13 +1,25 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image
try: try:
from PIL import ImageGrab from PIL import ImageGrab
except ImportError as v:
skip(v)
def test_grab(): class TestImageCopy(PillowTestCase):
im = ImageGrab.grab()
assert_image(im, im.mode, im.size) def test_grab(self):
im = ImageGrab.grab()
self.assert_image(im, im.mode, im.size)
def test_grab2(self):
im = ImageGrab.grab()
self.assert_image(im, im.mode, im.size)
except ImportError:
class TestImageCopy(PillowTestCase):
def test_skip(self):
self.skipTest("ImportError")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,14 +1,15 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
from PIL import ImageMath from PIL import ImageMath
def pixel(im): def pixel(im):
if hasattr(im, "im"): if hasattr(im, "im"):
return "%s %r" % (im.mode, im.getpixel((0, 0))) return "%s %r" % (im.mode, im.getpixel((0, 0)))
else: else:
if isinstance(im, type(0)): if isinstance(im, type(0)):
return int(im) # hack to deal with booleans return int(im) # hack to deal with booleans
print(im) print(im)
A = Image.new("L", (1, 1), 1) A = Image.new("L", (1, 1), 1)
@ -18,45 +19,60 @@ I = Image.new("I", (1, 1), 4)
images = {"A": A, "B": B, "F": F, "I": I} images = {"A": A, "B": B, "F": F, "I": I}
def test_sanity():
assert_equal(ImageMath.eval("1"), 1)
assert_equal(ImageMath.eval("1+A", A=2), 3)
assert_equal(pixel(ImageMath.eval("A+B", A=A, B=B)), "I 3")
assert_equal(pixel(ImageMath.eval("A+B", images)), "I 3")
assert_equal(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0")
assert_equal(pixel(ImageMath.eval("int(float(A)+B)", images)), "I 3")
def test_ops(): class TestImageMath(PillowTestCase):
assert_equal(pixel(ImageMath.eval("-A", images)), "I -1") def test_sanity(self):
assert_equal(pixel(ImageMath.eval("+B", images)), "L 2") self.assertEqual(ImageMath.eval("1"), 1)
self.assertEqual(ImageMath.eval("1+A", A=2), 3)
self.assertEqual(pixel(ImageMath.eval("A+B", A=A, B=B)), "I 3")
self.assertEqual(pixel(ImageMath.eval("A+B", images)), "I 3")
self.assertEqual(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0")
self.assertEqual(pixel(
ImageMath.eval("int(float(A)+B)", images)), "I 3")
assert_equal(pixel(ImageMath.eval("A+B", images)), "I 3") def test_ops(self):
assert_equal(pixel(ImageMath.eval("A-B", images)), "I -1")
assert_equal(pixel(ImageMath.eval("A*B", images)), "I 2")
assert_equal(pixel(ImageMath.eval("A/B", images)), "I 0")
assert_equal(pixel(ImageMath.eval("B**2", images)), "I 4")
assert_equal(pixel(ImageMath.eval("B**33", images)), "I 2147483647")
assert_equal(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0") self.assertEqual(pixel(ImageMath.eval("-A", images)), "I -1")
assert_equal(pixel(ImageMath.eval("float(A)-B", images)), "F -1.0") self.assertEqual(pixel(ImageMath.eval("+B", images)), "L 2")
assert_equal(pixel(ImageMath.eval("float(A)*B", images)), "F 2.0")
assert_equal(pixel(ImageMath.eval("float(A)/B", images)), "F 0.5")
assert_equal(pixel(ImageMath.eval("float(B)**2", images)), "F 4.0")
assert_equal(pixel(ImageMath.eval("float(B)**33", images)), "F 8589934592.0")
def test_logical(): self.assertEqual(pixel(ImageMath.eval("A+B", images)), "I 3")
assert_equal(pixel(ImageMath.eval("not A", images)), 0) self.assertEqual(pixel(ImageMath.eval("A-B", images)), "I -1")
assert_equal(pixel(ImageMath.eval("A and B", images)), "L 2") self.assertEqual(pixel(ImageMath.eval("A*B", images)), "I 2")
assert_equal(pixel(ImageMath.eval("A or B", images)), "L 1") self.assertEqual(pixel(ImageMath.eval("A/B", images)), "I 0")
self.assertEqual(pixel(ImageMath.eval("B**2", images)), "I 4")
self.assertEqual(pixel(
ImageMath.eval("B**33", images)), "I 2147483647")
def test_convert(): self.assertEqual(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0")
assert_equal(pixel(ImageMath.eval("convert(A+B, 'L')", images)), "L 3") self.assertEqual(pixel(ImageMath.eval("float(A)-B", images)), "F -1.0")
assert_equal(pixel(ImageMath.eval("convert(A+B, '1')", images)), "1 0") self.assertEqual(pixel(ImageMath.eval("float(A)*B", images)), "F 2.0")
assert_equal(pixel(ImageMath.eval("convert(A+B, 'RGB')", images)), "RGB (3, 3, 3)") self.assertEqual(pixel(ImageMath.eval("float(A)/B", images)), "F 0.5")
self.assertEqual(pixel(ImageMath.eval("float(B)**2", images)), "F 4.0")
self.assertEqual(pixel(
ImageMath.eval("float(B)**33", images)), "F 8589934592.0")
def test_compare(): def test_logical(self):
assert_equal(pixel(ImageMath.eval("min(A, B)", images)), "I 1") self.assertEqual(pixel(ImageMath.eval("not A", images)), 0)
assert_equal(pixel(ImageMath.eval("max(A, B)", images)), "I 2") self.assertEqual(pixel(ImageMath.eval("A and B", images)), "L 2")
assert_equal(pixel(ImageMath.eval("A == 1", images)), "I 1") self.assertEqual(pixel(ImageMath.eval("A or B", images)), "L 1")
assert_equal(pixel(ImageMath.eval("A == 2", images)), "I 0")
def test_convert(self):
self.assertEqual(pixel(
ImageMath.eval("convert(A+B, 'L')", images)), "L 3")
self.assertEqual(pixel(
ImageMath.eval("convert(A+B, '1')", images)), "1 0")
self.assertEqual(pixel(
ImageMath.eval("convert(A+B, 'RGB')", images)), "RGB (3, 3, 3)")
def test_compare(self):
self.assertEqual(pixel(ImageMath.eval("min(A, B)", images)), "I 1")
self.assertEqual(pixel(ImageMath.eval("max(A, B)", images)), "I 2")
self.assertEqual(pixel(ImageMath.eval("A == 1", images)), "I 1")
self.assertEqual(pixel(ImageMath.eval("A == 2", images)), "I 0")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,23 +1,32 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image
from PIL import ImageMode from PIL import ImageMode
ImageMode.getmode("1")
ImageMode.getmode("L")
ImageMode.getmode("P")
ImageMode.getmode("RGB")
ImageMode.getmode("I")
ImageMode.getmode("F")
m = ImageMode.getmode("1") class TestImageMode(PillowTestCase):
assert_equal(m.mode, "1")
assert_equal(m.bands, ("1",))
assert_equal(m.basemode, "L")
assert_equal(m.basetype, "L")
m = ImageMode.getmode("RGB") def test_sanity(self):
assert_equal(m.mode, "RGB") ImageMode.getmode("1")
assert_equal(m.bands, ("R", "G", "B")) ImageMode.getmode("L")
assert_equal(m.basemode, "RGB") ImageMode.getmode("P")
assert_equal(m.basetype, "L") ImageMode.getmode("RGB")
ImageMode.getmode("I")
ImageMode.getmode("F")
m = ImageMode.getmode("1")
self.assertEqual(m.mode, "1")
self.assertEqual(m.bands, ("1",))
self.assertEqual(m.basemode, "L")
self.assertEqual(m.basetype, "L")
m = ImageMode.getmode("RGB")
self.assertEqual(m.mode, "RGB")
self.assertEqual(m.bands, ("R", "G", "B"))
self.assertEqual(m.basemode, "RGB")
self.assertEqual(m.basetype, "L")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,81 +1,85 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
from PIL import ImageOps from PIL import ImageOps
class Deformer:
def getmesh(self, im):
x, y = im.size
return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]
deformer = Deformer() class TestImageOps(PillowTestCase):
def test_sanity(): class Deformer:
def getmesh(self, im):
x, y = im.size
return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]
ImageOps.autocontrast(lena("L")) deformer = Deformer()
ImageOps.autocontrast(lena("RGB"))
ImageOps.autocontrast(lena("L"), cutoff=10) def test_sanity(self):
ImageOps.autocontrast(lena("L"), ignore=[0, 255])
ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255)) ImageOps.autocontrast(lena("L"))
ImageOps.colorize(lena("L"), "black", "white") ImageOps.autocontrast(lena("RGB"))
ImageOps.crop(lena("L"), 1) ImageOps.autocontrast(lena("L"), cutoff=10)
ImageOps.crop(lena("RGB"), 1) ImageOps.autocontrast(lena("L"), ignore=[0, 255])
ImageOps.deform(lena("L"), deformer) ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255))
ImageOps.deform(lena("RGB"), deformer) ImageOps.colorize(lena("L"), "black", "white")
ImageOps.equalize(lena("L")) ImageOps.crop(lena("L"), 1)
ImageOps.equalize(lena("RGB")) ImageOps.crop(lena("RGB"), 1)
ImageOps.expand(lena("L"), 1) ImageOps.deform(lena("L"), self.deformer)
ImageOps.expand(lena("RGB"), 1) ImageOps.deform(lena("RGB"), self.deformer)
ImageOps.expand(lena("L"), 2, "blue")
ImageOps.expand(lena("RGB"), 2, "blue")
ImageOps.fit(lena("L"), (128, 128)) ImageOps.equalize(lena("L"))
ImageOps.fit(lena("RGB"), (128, 128)) ImageOps.equalize(lena("RGB"))
ImageOps.flip(lena("L")) ImageOps.expand(lena("L"), 1)
ImageOps.flip(lena("RGB")) ImageOps.expand(lena("RGB"), 1)
ImageOps.expand(lena("L"), 2, "blue")
ImageOps.expand(lena("RGB"), 2, "blue")
ImageOps.grayscale(lena("L")) ImageOps.fit(lena("L"), (128, 128))
ImageOps.grayscale(lena("RGB")) ImageOps.fit(lena("RGB"), (128, 128))
ImageOps.invert(lena("L")) ImageOps.flip(lena("L"))
ImageOps.invert(lena("RGB")) ImageOps.flip(lena("RGB"))
ImageOps.mirror(lena("L")) ImageOps.grayscale(lena("L"))
ImageOps.mirror(lena("RGB")) ImageOps.grayscale(lena("RGB"))
ImageOps.posterize(lena("L"), 4) ImageOps.invert(lena("L"))
ImageOps.posterize(lena("RGB"), 4) ImageOps.invert(lena("RGB"))
ImageOps.solarize(lena("L")) ImageOps.mirror(lena("L"))
ImageOps.solarize(lena("RGB")) ImageOps.mirror(lena("RGB"))
success() ImageOps.posterize(lena("L"), 4)
ImageOps.posterize(lena("RGB"), 4)
def test_1pxfit(): ImageOps.solarize(lena("L"))
# Division by zero in equalize if image is 1 pixel high ImageOps.solarize(lena("RGB"))
newimg = ImageOps.fit(lena("RGB").resize((1,1)), (35,35))
assert_equal(newimg.size,(35,35))
newimg = ImageOps.fit(lena("RGB").resize((1,100)), (35,35))
assert_equal(newimg.size,(35,35))
newimg = ImageOps.fit(lena("RGB").resize((100,1)), (35,35)) def test_1pxfit(self):
assert_equal(newimg.size,(35,35)) # Division by zero in equalize if image is 1 pixel high
newimg = ImageOps.fit(lena("RGB").resize((1, 1)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
def test_pil163(): newimg = ImageOps.fit(lena("RGB").resize((1, 100)), (35, 35))
# Division by zero in equalize if < 255 pixels in image (@PIL163) self.assertEqual(newimg.size, (35, 35))
i = lena("RGB").resize((15, 16)) newimg = ImageOps.fit(lena("RGB").resize((100, 1)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
ImageOps.equalize(i.convert("L")) def test_pil163(self):
ImageOps.equalize(i.convert("P")) # Division by zero in equalize if < 255 pixels in image (@PIL163)
ImageOps.equalize(i.convert("RGB"))
success() i = lena("RGB").resize((15, 16))
ImageOps.equalize(i.convert("L"))
ImageOps.equalize(i.convert("P"))
ImageOps.equalize(i.convert("RGB"))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
from PIL import ImageOps from PIL import ImageOps
@ -6,50 +6,59 @@ from PIL import ImageFilter
im = Image.open("Images/lena.ppm") im = Image.open("Images/lena.ppm")
def test_ops_api():
i = ImageOps.gaussian_blur(im, 2.0) class TestImageOpsUsm(PillowTestCase):
assert_equal(i.mode, "RGB")
assert_equal(i.size, (128, 128))
# i.save("blur.bmp")
i = ImageOps.usm(im, 2.0, 125, 8) def test_ops_api(self):
assert_equal(i.mode, "RGB")
assert_equal(i.size, (128, 128))
# i.save("usm.bmp")
def test_filter_api(): i = ImageOps.gaussian_blur(im, 2.0)
self.assertEqual(i.mode, "RGB")
self.assertEqual(i.size, (128, 128))
# i.save("blur.bmp")
filter = ImageFilter.GaussianBlur(2.0) i = ImageOps.usm(im, 2.0, 125, 8)
i = im.filter(filter) self.assertEqual(i.mode, "RGB")
assert_equal(i.mode, "RGB") self.assertEqual(i.size, (128, 128))
assert_equal(i.size, (128, 128)) # i.save("usm.bmp")
filter = ImageFilter.UnsharpMask(2.0, 125, 8) def test_filter_api(self):
i = im.filter(filter)
assert_equal(i.mode, "RGB")
assert_equal(i.size, (128, 128))
def test_usm(): filter = ImageFilter.GaussianBlur(2.0)
i = im.filter(filter)
self.assertEqual(i.mode, "RGB")
self.assertEqual(i.size, (128, 128))
usm = ImageOps.unsharp_mask filter = ImageFilter.UnsharpMask(2.0, 125, 8)
assert_exception(ValueError, lambda: usm(im.convert("1"))) i = im.filter(filter)
assert_no_exception(lambda: usm(im.convert("L"))) self.assertEqual(i.mode, "RGB")
assert_exception(ValueError, lambda: usm(im.convert("I"))) self.assertEqual(i.size, (128, 128))
assert_exception(ValueError, lambda: usm(im.convert("F")))
assert_no_exception(lambda: usm(im.convert("RGB")))
assert_no_exception(lambda: usm(im.convert("RGBA")))
assert_no_exception(lambda: usm(im.convert("CMYK")))
assert_exception(ValueError, lambda: usm(im.convert("YCbCr")))
def test_blur(): def test_usm(self):
blur = ImageOps.gaussian_blur usm = ImageOps.unsharp_mask
assert_exception(ValueError, lambda: blur(im.convert("1"))) self.assertRaises(ValueError, lambda: usm(im.convert("1")))
assert_no_exception(lambda: blur(im.convert("L"))) usm(im.convert("L"))
assert_exception(ValueError, lambda: blur(im.convert("I"))) self.assertRaises(ValueError, lambda: usm(im.convert("I")))
assert_exception(ValueError, lambda: blur(im.convert("F"))) self.assertRaises(ValueError, lambda: usm(im.convert("F")))
assert_no_exception(lambda: blur(im.convert("RGB"))) usm(im.convert("RGB"))
assert_no_exception(lambda: blur(im.convert("RGBA"))) usm(im.convert("RGBA"))
assert_no_exception(lambda: blur(im.convert("CMYK"))) usm(im.convert("CMYK"))
assert_exception(ValueError, lambda: blur(im.convert("YCbCr"))) self.assertRaises(ValueError, lambda: usm(im.convert("YCbCr")))
def test_blur(self):
blur = ImageOps.gaussian_blur
self.assertRaises(ValueError, lambda: blur(im.convert("1")))
blur(im.convert("L"))
self.assertRaises(ValueError, lambda: blur(im.convert("I")))
self.assertRaises(ValueError, lambda: blur(im.convert("F")))
blur(im.convert("RGB"))
blur(im.convert("RGBA"))
blur(im.convert("CMYK"))
self.assertRaises(ValueError, lambda: blur(im.convert("YCbCr")))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,44 +1,50 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image
from PIL import ImagePalette from PIL import ImagePalette
ImagePalette = ImagePalette.ImagePalette ImagePalette = ImagePalette.ImagePalette
def test_sanity():
assert_no_exception(lambda: ImagePalette("RGB", list(range(256))*3)) class TestImagePalette(PillowTestCase):
assert_exception(ValueError, lambda: ImagePalette("RGB", list(range(256))*2))
def test_getcolor(): def test_sanity(self):
palette = ImagePalette() ImagePalette("RGB", list(range(256))*3)
self.assertRaises(
ValueError, lambda: ImagePalette("RGB", list(range(256))*2))
map = {} def test_getcolor(self):
for i in range(256):
map[palette.getcolor((i, i, i))] = i
assert_equal(len(map), 256) palette = ImagePalette()
assert_exception(ValueError, lambda: palette.getcolor((1, 2, 3)))
def test_file(): map = {}
for i in range(256):
map[palette.getcolor((i, i, i))] = i
palette = ImagePalette() self.assertEqual(len(map), 256)
self.assertRaises(ValueError, lambda: palette.getcolor((1, 2, 3)))
file = tempfile("temp.lut") def test_file(self):
palette.save(file) palette = ImagePalette()
from PIL.ImagePalette import load, raw file = self.tempfile("temp.lut")
p = load(file) palette.save(file)
# load returns raw palette information from PIL.ImagePalette import load, raw
assert_equal(len(p[0]), 768)
assert_equal(p[1], "RGB")
p = raw(p[1], p[0]) p = load(file)
assert_true(isinstance(p, ImagePalette))
# load returns raw palette information
self.assertEqual(len(p[0]), 768)
self.assertEqual(p[1], "RGB")
p = raw(p[1], p[0])
self.assertIsInstance(p, ImagePalette)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,54 +1,68 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image
from PIL import ImagePath from PIL import ImagePath
import array import array
def test_path():
p = ImagePath.Path(list(range(10))) class TestImagePath(PillowTestCase):
# sequence interface def test_path(self):
assert_equal(len(p), 5)
assert_equal(p[0], (0.0, 1.0))
assert_equal(p[-1], (8.0, 9.0))
assert_equal(list(p[:1]), [(0.0, 1.0)])
assert_equal(list(p), [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)])
# method sanity check p = ImagePath.Path(list(range(10)))
assert_equal(p.tolist(), [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)])
assert_equal(p.tolist(1), [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
assert_equal(p.getbbox(), (0.0, 1.0, 8.0, 9.0)) # sequence interface
self.assertEqual(len(p), 5)
self.assertEqual(p[0], (0.0, 1.0))
self.assertEqual(p[-1], (8.0, 9.0))
self.assertEqual(list(p[:1]), [(0.0, 1.0)])
self.assertEqual(
list(p),
[(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)])
assert_equal(p.compact(5), 2) # method sanity check
assert_equal(list(p), [(0.0, 1.0), (4.0, 5.0), (8.0, 9.0)]) self.assertEqual(
p.tolist(),
[(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)])
self.assertEqual(
p.tolist(1),
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
p.transform((1,0,1,0,1,1)) self.assertEqual(p.getbbox(), (0.0, 1.0, 8.0, 9.0))
assert_equal(list(p), [(1.0, 2.0), (5.0, 6.0), (9.0, 10.0)])
# alternative constructors self.assertEqual(p.compact(5), 2)
p = ImagePath.Path([0, 1]) self.assertEqual(list(p), [(0.0, 1.0), (4.0, 5.0), (8.0, 9.0)])
assert_equal(list(p), [(0.0, 1.0)])
p = ImagePath.Path([0.0, 1.0])
assert_equal(list(p), [(0.0, 1.0)])
p = ImagePath.Path([0, 1])
assert_equal(list(p), [(0.0, 1.0)])
p = ImagePath.Path([(0, 1)])
assert_equal(list(p), [(0.0, 1.0)])
p = ImagePath.Path(p)
assert_equal(list(p), [(0.0, 1.0)])
p = ImagePath.Path(p.tolist(0))
assert_equal(list(p), [(0.0, 1.0)])
p = ImagePath.Path(p.tolist(1))
assert_equal(list(p), [(0.0, 1.0)])
p = ImagePath.Path(array.array("f", [0, 1]))
assert_equal(list(p), [(0.0, 1.0)])
arr = array.array("f", [0, 1]) p.transform((1, 0, 1, 0, 1, 1))
if hasattr(arr, 'tobytes'): self.assertEqual(list(p), [(1.0, 2.0), (5.0, 6.0), (9.0, 10.0)])
p = ImagePath.Path(arr.tobytes())
else: # alternative constructors
p = ImagePath.Path(arr.tostring()) p = ImagePath.Path([0, 1])
assert_equal(list(p), [(0.0, 1.0)]) self.assertEqual(list(p), [(0.0, 1.0)])
p = ImagePath.Path([0.0, 1.0])
self.assertEqual(list(p), [(0.0, 1.0)])
p = ImagePath.Path([0, 1])
self.assertEqual(list(p), [(0.0, 1.0)])
p = ImagePath.Path([(0, 1)])
self.assertEqual(list(p), [(0.0, 1.0)])
p = ImagePath.Path(p)
self.assertEqual(list(p), [(0.0, 1.0)])
p = ImagePath.Path(p.tolist(0))
self.assertEqual(list(p), [(0.0, 1.0)])
p = ImagePath.Path(p.tolist(1))
self.assertEqual(list(p), [(0.0, 1.0)])
p = ImagePath.Path(array.array("f", [0, 1]))
self.assertEqual(list(p), [(0.0, 1.0)])
arr = array.array("f", [0, 1])
if hasattr(arr, 'tobytes'):
p = ImagePath.Path(arr.tobytes())
else:
p = ImagePath.Path(arr.tostring())
self.assertEqual(list(p), [(0.0, 1.0)])
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,37 +1,53 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
try: try:
from PIL import ImageQt
from PyQt5.QtGui import QImage, qRgb, qRgba from PyQt5.QtGui import QImage, qRgb, qRgba
except: except:
try: try:
from PyQt4.QtGui import QImage, qRgb, qRgba from PyQt4.QtGui import QImage, qRgb, qRgba
except: except:
skip('PyQT4 or 5 not installed') # Will be skipped in setUp
pass
from PIL import ImageQt
def test_rgb():
# from https://qt-project.org/doc/qt-4.8/qcolor.html
# typedef QRgb
# An ARGB quadruplet on the format #AARRGGBB, equivalent to an unsigned int.
assert_equal(qRgb(0,0,0), qRgba(0,0,0,255))
def checkrgb(r,g,b):
val = ImageQt.rgb(r,g,b)
val = val % 2**24 # drop the alpha
assert_equal(val >> 16, r)
assert_equal(((val >> 8 ) % 2**8), g)
assert_equal(val % 2**8, b)
checkrgb(0,0,0)
checkrgb(255,0,0)
checkrgb(0,255,0)
checkrgb(0,0,255)
def test_image(): class TestImageQt(PillowTestCase):
for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
assert_no_exception(lambda: ImageQt.ImageQt(lena(mode))) def setUp(self):
try:
from PyQt5.QtGui import QImage, qRgb, qRgba
except:
try:
from PyQt4.QtGui import QImage, qRgb, qRgba
except:
self.skipTest('PyQt4 or 5 not installed')
def test_rgb(self):
# from https://qt-project.org/doc/qt-4.8/qcolor.html
# typedef QRgb
# An ARGB quadruplet on the format #AARRGGBB,
# equivalent to an unsigned int.
self.assertEqual(qRgb(0, 0, 0), qRgba(0, 0, 0, 255))
def checkrgb(r, g, b):
val = ImageQt.rgb(r, g, b)
val = val % 2**24 # drop the alpha
self.assertEqual(val >> 16, r)
self.assertEqual(((val >> 8) % 2**8), g)
self.assertEqual(val % 2**8, b)
checkrgb(0, 0, 0)
checkrgb(255, 0, 0)
checkrgb(0, 255, 0)
checkrgb(0, 0, 255)
def test_image(self):
for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
ImageQt.ImageQt(lena(mode))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,22 +1,29 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image
from PIL import ImageSequence from PIL import ImageSequence
def test_sanity():
file = tempfile("temp.im") class TestImageSequence(PillowTestCase):
im = lena("RGB") def test_sanity(self):
im.save(file)
seq = ImageSequence.Iterator(im) file = self.tempfile("temp.im")
index = 0 im = lena("RGB")
for frame in seq: im.save(file)
assert_image_equal(im, frame)
assert_equal(im.tell(), index)
index = index + 1
assert_equal(index, 1) seq = ImageSequence.Iterator(im)
index = 0
for frame in seq:
self.assert_image_equal(im, frame)
self.assertEqual(im.tell(), index)
index = index + 1
self.assertEqual(index, 1)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,6 +1,18 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
from PIL import ImageShow from PIL import ImageShow
success()
class TestImageShow(PillowTestCase):
def test_sanity(self):
dir(Image)
dir(ImageShow)
pass
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,52 +1,63 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
from PIL import ImageStat from PIL import ImageStat
def test_sanity():
im = lena() class TestImageStat(PillowTestCase):
st = ImageStat.Stat(im) def test_sanity(self):
st = ImageStat.Stat(im.histogram())
st = ImageStat.Stat(im, Image.new("1", im.size, 1))
assert_no_exception(lambda: st.extrema) im = lena()
assert_no_exception(lambda: st.sum)
assert_no_exception(lambda: st.mean)
assert_no_exception(lambda: st.median)
assert_no_exception(lambda: st.rms)
assert_no_exception(lambda: st.sum2)
assert_no_exception(lambda: st.var)
assert_no_exception(lambda: st.stddev)
assert_exception(AttributeError, lambda: st.spam)
assert_exception(TypeError, lambda: ImageStat.Stat(1)) st = ImageStat.Stat(im)
st = ImageStat.Stat(im.histogram())
st = ImageStat.Stat(im, Image.new("1", im.size, 1))
def test_lena(): # Check these run. Exceptions will cause failures.
st.extrema
st.sum
st.mean
st.median
st.rms
st.sum2
st.var
st.stddev
im = lena() self.assertRaises(AttributeError, lambda: st.spam)
st = ImageStat.Stat(im) self.assertRaises(TypeError, lambda: ImageStat.Stat(1))
# verify a few values def test_lena(self):
assert_equal(st.extrema[0], (61, 255))
assert_equal(st.median[0], 197)
assert_equal(st.sum[0], 2954416)
assert_equal(st.sum[1], 2027250)
assert_equal(st.sum[2], 1727331)
def test_constant(): im = lena()
im = Image.new("L", (128, 128), 128) st = ImageStat.Stat(im)
st = ImageStat.Stat(im) # verify a few values
self.assertEqual(st.extrema[0], (61, 255))
self.assertEqual(st.median[0], 197)
self.assertEqual(st.sum[0], 2954416)
self.assertEqual(st.sum[1], 2027250)
self.assertEqual(st.sum[2], 1727331)
assert_equal(st.extrema[0], (128, 128)) def test_constant(self):
assert_equal(st.sum[0], 128**3)
assert_equal(st.sum2[0], 128**4) im = Image.new("L", (128, 128), 128)
assert_equal(st.mean[0], 128)
assert_equal(st.median[0], 128) st = ImageStat.Stat(im)
assert_equal(st.rms[0], 128)
assert_equal(st.var[0], 0) self.assertEqual(st.extrema[0], (128, 128))
assert_equal(st.stddev[0], 0) self.assertEqual(st.sum[0], 128**3)
self.assertEqual(st.sum2[0], 128**4)
self.assertEqual(st.mean[0], 128)
self.assertEqual(st.median[0], 128)
self.assertEqual(st.rms[0], 128)
self.assertEqual(st.var[0], 0)
self.assertEqual(st.stddev[0], 0)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,9 +1,17 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image
try:
from PIL import ImageTk
except (OSError, ImportError) as v:
skip(v)
success() class TestImageTk(PillowTestCase):
def test_import(self):
try:
from PIL import ImageTk
dir(ImageTk)
except (OSError, ImportError) as v:
self.skipTest(v)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,18 +1,27 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
from PIL import ImageTransform from PIL import ImageTransform
im = Image.new("L", (100, 100))
seq = tuple(range(10)) class TestImageTransform(PillowTestCase):
def test_sanity(): def test_sanity(self):
transform = ImageTransform.AffineTransform(seq[:6]) im = Image.new("L", (100, 100))
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.ExtentTransform(seq[:4]) seq = tuple(range(10))
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.QuadTransform(seq[:8]) transform = ImageTransform.AffineTransform(seq[:6])
assert_no_exception(lambda: im.transform((100, 100), transform)) im.transform((100, 100), transform)
transform = ImageTransform.MeshTransform([(seq[:4], seq[:8])]) transform = ImageTransform.ExtentTransform(seq[:4])
assert_no_exception(lambda: im.transform((100, 100), transform)) im.transform((100, 100), transform)
transform = ImageTransform.QuadTransform(seq[:8])
im.transform((100, 100), transform)
transform = ImageTransform.MeshTransform([(seq[:4], seq[:8])])
im.transform((100, 100), transform)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,6 +1,18 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
from PIL import ImageWin from PIL import ImageWin
success()
class TestImageWin(PillowTestCase):
def test_sanity(self):
dir(Image)
dir(ImageWin)
pass
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,30 +1,39 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
def test_setmode():
im = Image.new("L", (1, 1), 255) class TestSanity(PillowTestCase):
im.im.setmode("1")
assert_equal(im.im.getpixel((0, 0)), 255)
im.im.setmode("L")
assert_equal(im.im.getpixel((0, 0)), 255)
im = Image.new("1", (1, 1), 1) def test_setmode(self):
im.im.setmode("L")
assert_equal(im.im.getpixel((0, 0)), 255)
im.im.setmode("1")
assert_equal(im.im.getpixel((0, 0)), 255)
im = Image.new("RGB", (1, 1), (1, 2, 3)) im = Image.new("L", (1, 1), 255)
im.im.setmode("RGB") im.im.setmode("1")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3)) self.assertEqual(im.im.getpixel((0, 0)), 255)
im.im.setmode("RGBA") im.im.setmode("L")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3, 255)) self.assertEqual(im.im.getpixel((0, 0)), 255)
im.im.setmode("RGBX")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3, 255))
im.im.setmode("RGB")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3))
assert_exception(ValueError, lambda: im.im.setmode("L")) im = Image.new("1", (1, 1), 1)
assert_exception(ValueError, lambda: im.im.setmode("RGBABCDE")) im.im.setmode("L")
self.assertEqual(im.im.getpixel((0, 0)), 255)
im.im.setmode("1")
self.assertEqual(im.im.getpixel((0, 0)), 255)
im = Image.new("RGB", (1, 1), (1, 2, 3))
im.im.setmode("RGB")
self.assertEqual(im.im.getpixel((0, 0)), (1, 2, 3))
im.im.setmode("RGBA")
self.assertEqual(im.im.getpixel((0, 0)), (1, 2, 3, 255))
im.im.setmode("RGBX")
self.assertEqual(im.im.getpixel((0, 0)), (1, 2, 3, 255))
im.im.setmode("RGB")
self.assertEqual(im.im.getpixel((0, 0)), (1, 2, 3))
self.assertRaises(ValueError, lambda: im.im.setmode("L"))
self.assertRaises(ValueError, lambda: im.im.setmode("RGBABCDE"))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,138 +1,147 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, py3
from PIL import Image from PIL import Image
def pack():
pass # not yet
def test_pack(): class TestLibPack(PillowTestCase):
def pack(mode, rawmode): def pack(self):
if len(mode) == 1: pass # not yet
im = Image.new(mode, (1, 1), 1)
else:
im = Image.new(mode, (1, 1), (1, 2, 3, 4)[:len(mode)])
if py3: def test_pack(self):
return list(im.tobytes("raw", rawmode))
else:
return [ord(c) for c in im.tobytes("raw", rawmode)]
order = 1 if Image._ENDIAN == '<' else -1 def pack(mode, rawmode):
if len(mode) == 1:
im = Image.new(mode, (1, 1), 1)
else:
im = Image.new(mode, (1, 1), (1, 2, 3, 4)[:len(mode)])
assert_equal(pack("1", "1"), [128]) if py3:
assert_equal(pack("1", "1;I"), [0]) return list(im.tobytes("raw", rawmode))
assert_equal(pack("1", "1;R"), [1]) else:
assert_equal(pack("1", "1;IR"), [0]) return [ord(c) for c in im.tobytes("raw", rawmode)]
assert_equal(pack("L", "L"), [1]) order = 1 if Image._ENDIAN == '<' else -1
assert_equal(pack("I", "I"), [1, 0, 0, 0][::order]) self.assertEqual(pack("1", "1"), [128])
self.assertEqual(pack("1", "1;I"), [0])
self.assertEqual(pack("1", "1;R"), [1])
self.assertEqual(pack("1", "1;IR"), [0])
assert_equal(pack("F", "F"), [0, 0, 128, 63][::order]) self.assertEqual(pack("L", "L"), [1])
assert_equal(pack("LA", "LA"), [1, 2]) self.assertEqual(pack("I", "I"), [1, 0, 0, 0][::order])
assert_equal(pack("RGB", "RGB"), [1, 2, 3]) self.assertEqual(pack("F", "F"), [0, 0, 128, 63][::order])
assert_equal(pack("RGB", "RGB;L"), [1, 2, 3])
assert_equal(pack("RGB", "BGR"), [3, 2, 1])
assert_equal(pack("RGB", "RGBX"), [1, 2, 3, 255]) # 255?
assert_equal(pack("RGB", "BGRX"), [3, 2, 1, 0])
assert_equal(pack("RGB", "XRGB"), [0, 1, 2, 3])
assert_equal(pack("RGB", "XBGR"), [0, 3, 2, 1])
assert_equal(pack("RGBX", "RGBX"), [1, 2, 3, 4]) # 4->255? self.assertEqual(pack("LA", "LA"), [1, 2])
assert_equal(pack("RGBA", "RGBA"), [1, 2, 3, 4]) self.assertEqual(pack("RGB", "RGB"), [1, 2, 3])
self.assertEqual(pack("RGB", "RGB;L"), [1, 2, 3])
self.assertEqual(pack("RGB", "BGR"), [3, 2, 1])
self.assertEqual(pack("RGB", "RGBX"), [1, 2, 3, 255]) # 255?
self.assertEqual(pack("RGB", "BGRX"), [3, 2, 1, 0])
self.assertEqual(pack("RGB", "XRGB"), [0, 1, 2, 3])
self.assertEqual(pack("RGB", "XBGR"), [0, 3, 2, 1])
assert_equal(pack("CMYK", "CMYK"), [1, 2, 3, 4]) self.assertEqual(pack("RGBX", "RGBX"), [1, 2, 3, 4]) # 4->255?
assert_equal(pack("YCbCr", "YCbCr"), [1, 2, 3])
def test_unpack(): self.assertEqual(pack("RGBA", "RGBA"), [1, 2, 3, 4])
def unpack(mode, rawmode, bytes_): self.assertEqual(pack("CMYK", "CMYK"), [1, 2, 3, 4])
im = None self.assertEqual(pack("YCbCr", "YCbCr"), [1, 2, 3])
if py3: def test_unpack(self):
data = bytes(range(1,bytes_+1))
else:
data = ''.join(chr(i) for i in range(1,bytes_+1))
im = Image.frombytes(mode, (1, 1), data, "raw", rawmode, 0, 1) def unpack(mode, rawmode, bytes_):
im = None
return im.getpixel((0, 0)) if py3:
data = bytes(range(1, bytes_+1))
else:
data = ''.join(chr(i) for i in range(1, bytes_+1))
def unpack_1(mode, rawmode, value): im = Image.frombytes(mode, (1, 1), data, "raw", rawmode, 0, 1)
assert mode == "1"
im = None
if py3: return im.getpixel((0, 0))
im = Image.frombytes(mode, (8, 1), bytes([value]), "raw", rawmode, 0, 1)
else:
im = Image.frombytes(mode, (8, 1), chr(value), "raw", rawmode, 0, 1)
return tuple(im.getdata()) def unpack_1(mode, rawmode, value):
assert mode == "1"
im = None
X = 255 if py3:
im = Image.frombytes(
mode, (8, 1), bytes([value]), "raw", rawmode, 0, 1)
else:
im = Image.frombytes(
mode, (8, 1), chr(value), "raw", rawmode, 0, 1)
assert_equal(unpack_1("1", "1", 1), (0,0,0,0,0,0,0,X)) return tuple(im.getdata())
assert_equal(unpack_1("1", "1;I", 1), (X,X,X,X,X,X,X,0))
assert_equal(unpack_1("1", "1;R", 1), (X,0,0,0,0,0,0,0))
assert_equal(unpack_1("1", "1;IR", 1), (0,X,X,X,X,X,X,X))
assert_equal(unpack_1("1", "1", 170), (X,0,X,0,X,0,X,0)) X = 255
assert_equal(unpack_1("1", "1;I", 170), (0,X,0,X,0,X,0,X))
assert_equal(unpack_1("1", "1;R", 170), (0,X,0,X,0,X,0,X))
assert_equal(unpack_1("1", "1;IR", 170), (X,0,X,0,X,0,X,0))
assert_equal(unpack("L", "L;2", 1), 0) self.assertEqual(unpack_1("1", "1", 1), (0, 0, 0, 0, 0, 0, 0, X))
assert_equal(unpack("L", "L;4", 1), 0) self.assertEqual(unpack_1("1", "1;I", 1), (X, X, X, X, X, X, X, 0))
assert_equal(unpack("L", "L", 1), 1) self.assertEqual(unpack_1("1", "1;R", 1), (X, 0, 0, 0, 0, 0, 0, 0))
assert_equal(unpack("L", "L;I", 1), 254) self.assertEqual(unpack_1("1", "1;IR", 1), (0, X, X, X, X, X, X, X))
assert_equal(unpack("L", "L;R", 1), 128)
assert_equal(unpack("L", "L;16", 2), 2) # little endian
assert_equal(unpack("L", "L;16B", 2), 1) # big endian
assert_equal(unpack("LA", "LA", 2), (1, 2)) self.assertEqual(unpack_1("1", "1", 170), (X, 0, X, 0, X, 0, X, 0))
assert_equal(unpack("LA", "LA;L", 2), (1, 2)) self.assertEqual(unpack_1("1", "1;I", 170), (0, X, 0, X, 0, X, 0, X))
self.assertEqual(unpack_1("1", "1;R", 170), (0, X, 0, X, 0, X, 0, X))
self.assertEqual(unpack_1("1", "1;IR", 170), (X, 0, X, 0, X, 0, X, 0))
assert_equal(unpack("RGB", "RGB", 3), (1, 2, 3)) self.assertEqual(unpack("L", "L;2", 1), 0)
assert_equal(unpack("RGB", "RGB;L", 3), (1, 2, 3)) self.assertEqual(unpack("L", "L;4", 1), 0)
assert_equal(unpack("RGB", "RGB;R", 3), (128, 64, 192)) self.assertEqual(unpack("L", "L", 1), 1)
assert_equal(unpack("RGB", "RGB;16B", 6), (1, 3, 5)) # ? self.assertEqual(unpack("L", "L;I", 1), 254)
assert_equal(unpack("RGB", "BGR", 3), (3, 2, 1)) self.assertEqual(unpack("L", "L;R", 1), 128)
assert_equal(unpack("RGB", "RGB;15", 2), (8, 131, 0)) self.assertEqual(unpack("L", "L;16", 2), 2) # little endian
assert_equal(unpack("RGB", "BGR;15", 2), (0, 131, 8)) self.assertEqual(unpack("L", "L;16B", 2), 1) # big endian
assert_equal(unpack("RGB", "RGB;16", 2), (8, 64, 0))
assert_equal(unpack("RGB", "BGR;16", 2), (0, 64, 8))
assert_equal(unpack("RGB", "RGB;4B", 2), (17, 0, 34))
assert_equal(unpack("RGB", "RGBX", 4), (1, 2, 3)) self.assertEqual(unpack("LA", "LA", 2), (1, 2))
assert_equal(unpack("RGB", "BGRX", 4), (3, 2, 1)) self.assertEqual(unpack("LA", "LA;L", 2), (1, 2))
assert_equal(unpack("RGB", "XRGB", 4), (2, 3, 4))
assert_equal(unpack("RGB", "XBGR", 4), (4, 3, 2))
assert_equal(unpack("RGBA", "RGBA", 4), (1, 2, 3, 4)) self.assertEqual(unpack("RGB", "RGB", 3), (1, 2, 3))
assert_equal(unpack("RGBA", "BGRA", 4), (3, 2, 1, 4)) self.assertEqual(unpack("RGB", "RGB;L", 3), (1, 2, 3))
assert_equal(unpack("RGBA", "ARGB", 4), (2, 3, 4, 1)) self.assertEqual(unpack("RGB", "RGB;R", 3), (128, 64, 192))
assert_equal(unpack("RGBA", "ABGR", 4), (4, 3, 2, 1)) self.assertEqual(unpack("RGB", "RGB;16B", 6), (1, 3, 5)) # ?
assert_equal(unpack("RGBA", "RGBA;15", 2), (8, 131, 0, 0)) self.assertEqual(unpack("RGB", "BGR", 3), (3, 2, 1))
assert_equal(unpack("RGBA", "BGRA;15", 2), (0, 131, 8, 0)) self.assertEqual(unpack("RGB", "RGB;15", 2), (8, 131, 0))
assert_equal(unpack("RGBA", "RGBA;4B", 2), (17, 0, 34, 0)) self.assertEqual(unpack("RGB", "BGR;15", 2), (0, 131, 8))
self.assertEqual(unpack("RGB", "RGB;16", 2), (8, 64, 0))
self.assertEqual(unpack("RGB", "BGR;16", 2), (0, 64, 8))
self.assertEqual(unpack("RGB", "RGB;4B", 2), (17, 0, 34))
assert_equal(unpack("RGBX", "RGBX", 4), (1, 2, 3, 4)) # 4->255? self.assertEqual(unpack("RGB", "RGBX", 4), (1, 2, 3))
assert_equal(unpack("RGBX", "BGRX", 4), (3, 2, 1, 255)) self.assertEqual(unpack("RGB", "BGRX", 4), (3, 2, 1))
assert_equal(unpack("RGBX", "XRGB", 4), (2, 3, 4, 255)) self.assertEqual(unpack("RGB", "XRGB", 4), (2, 3, 4))
assert_equal(unpack("RGBX", "XBGR", 4), (4, 3, 2, 255)) self.assertEqual(unpack("RGB", "XBGR", 4), (4, 3, 2))
assert_equal(unpack("RGBX", "RGB;15", 2), (8, 131, 0, 255))
assert_equal(unpack("RGBX", "BGR;15", 2), (0, 131, 8, 255))
assert_equal(unpack("RGBX", "RGB;4B", 2), (17, 0, 34, 255))
assert_equal(unpack("CMYK", "CMYK", 4), (1, 2, 3, 4)) self.assertEqual(unpack("RGBA", "RGBA", 4), (1, 2, 3, 4))
assert_equal(unpack("CMYK", "CMYK;I", 4), (254, 253, 252, 251)) self.assertEqual(unpack("RGBA", "BGRA", 4), (3, 2, 1, 4))
self.assertEqual(unpack("RGBA", "ARGB", 4), (2, 3, 4, 1))
self.assertEqual(unpack("RGBA", "ABGR", 4), (4, 3, 2, 1))
self.assertEqual(unpack("RGBA", "RGBA;15", 2), (8, 131, 0, 0))
self.assertEqual(unpack("RGBA", "BGRA;15", 2), (0, 131, 8, 0))
self.assertEqual(unpack("RGBA", "RGBA;4B", 2), (17, 0, 34, 0))
assert_exception(ValueError, lambda: unpack("L", "L", 0)) self.assertEqual(unpack("RGBX", "RGBX", 4), (1, 2, 3, 4)) # 4->255?
assert_exception(ValueError, lambda: unpack("RGB", "RGB", 2)) self.assertEqual(unpack("RGBX", "BGRX", 4), (3, 2, 1, 255))
assert_exception(ValueError, lambda: unpack("CMYK", "CMYK", 2)) self.assertEqual(unpack("RGBX", "XRGB", 4), (2, 3, 4, 255))
self.assertEqual(unpack("RGBX", "XBGR", 4), (4, 3, 2, 255))
self.assertEqual(unpack("RGBX", "RGB;15", 2), (8, 131, 0, 255))
self.assertEqual(unpack("RGBX", "BGR;15", 2), (0, 131, 8, 255))
self.assertEqual(unpack("RGBX", "RGB;4B", 2), (17, 0, 34, 255))
run() self.assertEqual(unpack("CMYK", "CMYK", 4), (1, 2, 3, 4))
self.assertEqual(unpack("CMYK", "CMYK;I", 4), (254, 253, 252, 251))
self.assertRaises(ValueError, lambda: unpack("L", "L", 0))
self.assertRaises(ValueError, lambda: unpack("RGB", "RGB", 2))
self.assertRaises(ValueError, lambda: unpack("CMYK", "CMYK", 2))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,31 +1,39 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
import locale import locale
# ref https://github.com/python-pillow/Pillow/issues/272 # ref https://github.com/python-pillow/Pillow/issues/272
## on windows, in polish locale: # on windows, in polish locale:
## import locale # import locale
## print locale.setlocale(locale.LC_ALL, 'polish') # print locale.setlocale(locale.LC_ALL, 'polish')
## import string # import string
## print len(string.whitespace) # print len(string.whitespace)
## print ord(string.whitespace[6]) # print ord(string.whitespace[6])
## Polish_Poland.1250 # Polish_Poland.1250
## 7 # 7
## 160 # 160
# one of string.whitespace is not freely convertable into ascii. # one of string.whitespace is not freely convertable into ascii.
path = "Images/lena.jpg" path = "Images/lena.jpg"
def test_sanity():
assert_no_exception(lambda: Image.open(path))
try:
locale.setlocale(locale.LC_ALL, "polish")
except:
skip('polish locale not available')
import string
assert_no_exception(lambda: Image.open(path))
class TestLocale(PillowTestCase):
def test_sanity(self):
Image.open(path)
try:
locale.setlocale(locale.LC_ALL, "polish")
except:
unittest.skip('Polish locale not available')
Image.open(path)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,107 +1,109 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
def verify(im1): class TestModeI16(PillowTestCase):
im2 = lena("I")
assert_equal(im1.size, im2.size) def verify(self, im1):
pix1 = im1.load() im2 = lena("I")
pix2 = im2.load() self.assertEqual(im1.size, im2.size)
for y in range(im1.size[1]): pix1 = im1.load()
for x in range(im1.size[0]): pix2 = im2.load()
xy = x, y for y in range(im1.size[1]):
if pix1[xy] != pix2[xy]: for x in range(im1.size[0]):
failure( xy = x, y
"got %r from mode %s at %s, expected %r" % self.assertEqual(
(pix1[xy], im1.mode, xy, pix2[xy]) pix1[xy], pix2[xy],
) ("got %r from mode %s at %s, expected %r" %
return (pix1[xy], im1.mode, xy, pix2[xy])))
success()
def test_basic(self):
# PIL 1.1 has limited support for 16-bit image data. Check that
# create/copy/transform and save works as expected.
def basic(mode):
imIn = lena("I").convert(mode)
self.verify(imIn)
w, h = imIn.size
imOut = imIn.copy()
self.verify(imOut) # copy
imOut = imIn.transform((w, h), Image.EXTENT, (0, 0, w, h))
self.verify(imOut) # transform
filename = self.tempfile("temp.im")
imIn.save(filename)
imOut = Image.open(filename)
self.verify(imIn)
self.verify(imOut)
imOut = imIn.crop((0, 0, w, h))
self.verify(imOut)
imOut = Image.new(mode, (w, h), None)
imOut.paste(imIn.crop((0, 0, w//2, h)), (0, 0))
imOut.paste(imIn.crop((w//2, 0, w, h)), (w//2, 0))
self.verify(imIn)
self.verify(imOut)
imIn = Image.new(mode, (1, 1), 1)
self.assertEqual(imIn.getpixel((0, 0)), 1)
imIn.putpixel((0, 0), 2)
self.assertEqual(imIn.getpixel((0, 0)), 2)
if mode == "L":
max = 255
else:
max = 32767
imIn = Image.new(mode, (1, 1), 256)
self.assertEqual(imIn.getpixel((0, 0)), min(256, max))
imIn.putpixel((0, 0), 512)
self.assertEqual(imIn.getpixel((0, 0)), min(512, max))
basic("L")
basic("I;16")
basic("I;16B")
basic("I;16L")
basic("I")
def test_tobytes(self):
def tobytes(mode):
return Image.new(mode, (1, 1), 1).tobytes()
order = 1 if Image._ENDIAN == '<' else -1
self.assertEqual(tobytes("L"), b"\x01")
self.assertEqual(tobytes("I;16"), b"\x01\x00")
self.assertEqual(tobytes("I;16B"), b"\x00\x01")
self.assertEqual(tobytes("I"), b"\x01\x00\x00\x00"[::order])
def test_convert(self):
im = lena("I")
self.verify(im.convert("I;16"))
self.verify(im.convert("I;16").convert("L"))
self.verify(im.convert("I;16").convert("I"))
self.verify(im.convert("I;16B"))
self.verify(im.convert("I;16B").convert("L"))
self.verify(im.convert("I;16B").convert("I"))
def test_basic(): if __name__ == '__main__':
# PIL 1.1 has limited support for 16-bit image data. Check that unittest.main()
# create/copy/transform and save works as expected.
def basic(mode): # End of file
imIn = lena("I").convert(mode)
verify(imIn)
w, h = imIn.size
imOut = imIn.copy()
verify(imOut) # copy
imOut = imIn.transform((w, h), Image.EXTENT, (0, 0, w, h))
verify(imOut) # transform
filename = tempfile("temp.im")
imIn.save(filename)
imOut = Image.open(filename)
verify(imIn)
verify(imOut)
imOut = imIn.crop((0, 0, w, h))
verify(imOut)
imOut = Image.new(mode, (w, h), None)
imOut.paste(imIn.crop((0, 0, w//2, h)), (0, 0))
imOut.paste(imIn.crop((w//2, 0, w, h)), (w//2, 0))
verify(imIn)
verify(imOut)
imIn = Image.new(mode, (1, 1), 1)
assert_equal(imIn.getpixel((0, 0)), 1)
imIn.putpixel((0, 0), 2)
assert_equal(imIn.getpixel((0, 0)), 2)
if mode == "L":
max = 255
else:
max = 32767
imIn = Image.new(mode, (1, 1), 256)
assert_equal(imIn.getpixel((0, 0)), min(256, max))
imIn.putpixel((0, 0), 512)
assert_equal(imIn.getpixel((0, 0)), min(512, max))
basic("L")
basic("I;16")
basic("I;16B")
basic("I;16L")
basic("I")
def test_tobytes():
def tobytes(mode):
return Image.new(mode, (1, 1), 1).tobytes()
order = 1 if Image._ENDIAN == '<' else -1
assert_equal(tobytes("L"), b"\x01")
assert_equal(tobytes("I;16"), b"\x01\x00")
assert_equal(tobytes("I;16B"), b"\x00\x01")
assert_equal(tobytes("I"), b"\x01\x00\x00\x00"[::order])
def test_convert():
im = lena("I")
verify(im.convert("I;16"))
verify(im.convert("I;16").convert("L"))
verify(im.convert("I;16").convert("I"))
verify(im.convert("I;16B"))
verify(im.convert("I;16B").convert("L"))
verify(im.convert("I;16B").convert("I"))

View File

@ -1,120 +1,128 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule, lena
from PIL import Image from PIL import Image
import struct
try: try:
import site import site
import numpy import numpy
except ImportError: except ImportError:
skip() # Skip via setUp()
pass
def test_numpy_to_image():
def to_image(dtype, bands=1, bool=0): class TestNumpy(PillowTestCase):
if bands == 1:
if bool: def setUp(self):
data = [0, 1] * 50 try:
import site
import numpy
except ImportError:
self.skipTest("ImportError")
def test_numpy_to_image(self):
def to_image(dtype, bands=1, bool=0):
if bands == 1:
if bool:
data = [0, 1] * 50
else:
data = list(range(100))
a = numpy.array(data, dtype=dtype)
a.shape = 10, 10
i = Image.fromarray(a)
if list(i.getdata()) != data:
print("data mismatch for", dtype)
else: else:
data = list(range(100)) data = list(range(100))
a = numpy.array(data, dtype=dtype) a = numpy.array([[x]*bands for x in data], dtype=dtype)
a.shape = 10, 10 a.shape = 10, 10, bands
i = Image.fromarray(a) i = Image.fromarray(a)
if list(i.getdata()) != data: if list(i.split()[0].getdata()) != list(range(100)):
print("data mismatch for", dtype) print("data mismatch for", dtype)
# print dtype, list(i.getdata())
return i
# self.assert_image(to_image(numpy.bool, bool=1), "1", (10, 10))
# self.assert_image(to_image(numpy.bool8, bool=1), "1", (10, 10))
self.assertRaises(TypeError, lambda: to_image(numpy.uint))
self.assert_image(to_image(numpy.uint8), "L", (10, 10))
self.assertRaises(TypeError, lambda: to_image(numpy.uint16))
self.assertRaises(TypeError, lambda: to_image(numpy.uint32))
self.assertRaises(TypeError, lambda: to_image(numpy.uint64))
self.assert_image(to_image(numpy.int8), "I", (10, 10))
if Image._ENDIAN == '<': # Little endian
self.assert_image(to_image(numpy.int16), "I;16", (10, 10))
else: else:
data = list(range(100)) self.assert_image(to_image(numpy.int16), "I;16B", (10, 10))
a = numpy.array([[x]*bands for x in data], dtype=dtype) self.assert_image(to_image(numpy.int32), "I", (10, 10))
a.shape = 10, 10, bands self.assertRaises(TypeError, lambda: to_image(numpy.int64))
i = Image.fromarray(a)
if list(i.split()[0].getdata()) != list(range(100)):
print("data mismatch for", dtype)
# print dtype, list(i.getdata())
return i
# assert_image(to_image(numpy.bool, bool=1), "1", (10, 10)) self.assert_image(to_image(numpy.float), "F", (10, 10))
# assert_image(to_image(numpy.bool8, bool=1), "1", (10, 10)) self.assert_image(to_image(numpy.float32), "F", (10, 10))
self.assert_image(to_image(numpy.float64), "F", (10, 10))
assert_exception(TypeError, lambda: to_image(numpy.uint)) self.assert_image(to_image(numpy.uint8, 3), "RGB", (10, 10))
assert_image(to_image(numpy.uint8), "L", (10, 10)) self.assert_image(to_image(numpy.uint8, 4), "RGBA", (10, 10))
assert_exception(TypeError, lambda: to_image(numpy.uint16))
assert_exception(TypeError, lambda: to_image(numpy.uint32))
assert_exception(TypeError, lambda: to_image(numpy.uint64))
assert_image(to_image(numpy.int8), "I", (10, 10)) # based on an erring example at http://is.gd/6F0esS (which resolves to)
if Image._ENDIAN == '<': # Little endian # http://stackoverflow.com/questions/10854903/what-is-causing-dimension-dependent-attributeerror-in-pil-fromarray-function
assert_image(to_image(numpy.int16), "I;16", (10, 10)) def test_3d_array(self):
else: a = numpy.ones((10, 10, 10), dtype=numpy.uint8)
assert_image(to_image(numpy.int16), "I;16B", (10, 10)) self.assert_image(Image.fromarray(a[1, :, :]), "L", (10, 10))
assert_image(to_image(numpy.int32), "I", (10, 10)) self.assert_image(Image.fromarray(a[:, 1, :]), "L", (10, 10))
assert_exception(TypeError, lambda: to_image(numpy.int64)) self.assert_image(Image.fromarray(a[:, :, 1]), "L", (10, 10))
assert_image(to_image(numpy.float), "F", (10, 10)) def _test_img_equals_nparray(self, img, np):
assert_image(to_image(numpy.float32), "F", (10, 10)) self.assertEqual(img.size, np.shape[0:2])
assert_image(to_image(numpy.float64), "F", (10, 10)) px = img.load()
for x in range(0, img.size[0], int(img.size[0]/10)):
for y in range(0, img.size[1], int(img.size[1]/10)):
self.assert_deep_equal(px[x, y], np[y, x])
assert_image(to_image(numpy.uint8, 3), "RGB", (10, 10)) def test_16bit(self):
assert_image(to_image(numpy.uint8, 4), "RGBA", (10, 10)) img = Image.open('Tests/images/16bit.cropped.tif')
# based on an erring example at http://is.gd/6F0esS (which resolves to)
# http://stackoverflow.com/questions/10854903/what-is-causing-dimension-dependent-attributeerror-in-pil-fromarray-function
def test_3d_array():
a = numpy.ones((10, 10, 10), dtype=numpy.uint8)
assert_image(Image.fromarray(a[1, :, :]), "L", (10, 10))
assert_image(Image.fromarray(a[:, 1, :]), "L", (10, 10))
assert_image(Image.fromarray(a[:, :, 1]), "L", (10, 10))
def _test_img_equals_nparray(img, np):
assert_equal(img.size, np.shape[0:2])
px = img.load()
for x in range(0, img.size[0], int(img.size[0]/10)):
for y in range(0, img.size[1], int(img.size[1]/10)):
assert_deep_equal(px[x,y], np[y,x])
def test_16bit():
img = Image.open('Tests/images/16bit.cropped.tif')
np_img = numpy.array(img)
_test_img_equals_nparray(img, np_img)
assert_equal(np_img.dtype, numpy.dtype('<u2'))
def test_to_array():
def _to_array(mode, dtype):
img = lena(mode)
np_img = numpy.array(img) np_img = numpy.array(img)
_test_img_equals_nparray(img, np_img) self._test_img_equals_nparray(img, np_img)
assert_equal(np_img.dtype, numpy.dtype(dtype)) self.assertEqual(np_img.dtype, numpy.dtype('<u2'))
def test_to_array(self):
def _to_array(mode, dtype):
img = lena(mode)
np_img = numpy.array(img)
self._test_img_equals_nparray(img, np_img)
self.assertEqual(np_img.dtype, numpy.dtype(dtype))
modes = [("L", 'uint8'),
("I", 'int32'),
("F", 'float32'),
("RGB", 'uint8'),
("RGBA", 'uint8'),
("RGBX", 'uint8'),
("CMYK", 'uint8'),
("YCbCr", 'uint8'),
("I;16", '<u2'),
("I;16B", '>u2'),
("I;16L", '<u2'),
]
for mode in modes:
_to_array(*mode)
def test_point_lut(self):
# see https://github.com/python-pillow/Pillow/issues/439
data = list(range(256))*3
lut = numpy.array(data, dtype='uint8')
im = lena()
im.point(lut)
modes = [("L", 'uint8'), if __name__ == '__main__':
("I", 'int32'), unittest.main()
("F", 'float32'),
("RGB", 'uint8'),
("RGBA", 'uint8'),
("RGBX", 'uint8'),
("CMYK", 'uint8'),
("YCbCr", 'uint8'),
("I;16", '<u2'),
("I;16B", '>u2'),
("I;16L", '<u2'),
]
for mode in modes:
assert_no_exception(lambda: _to_array(*mode))
def test_point_lut():
# see https://github.com/python-pillow/Pillow/issues/439
data = list(range(256))*3
lut = numpy.array(data, dtype='uint8')
im = lena()
assert_no_exception(lambda: im.point(lut))
# End of file

View File

@ -1,162 +1,155 @@
from __future__ import print_function from helper import unittest, PillowTestCase, tearDownModule
from tester import *
import datetime import datetime
import PIL.OleFileIO as OleFileIO import PIL.OleFileIO as OleFileIO
def test_isOleFile_false(): class TestOleFileIo(PillowTestCase):
# Arrange
non_ole_file = "Tests/images/flower.jpg"
# Act def test_isOleFile_false(self):
is_ole = OleFileIO.isOleFile(non_ole_file) # Arrange
non_ole_file = "Tests/images/flower.jpg"
# Assert # Act
assert_false(is_ole) is_ole = OleFileIO.isOleFile(non_ole_file)
# Assert
self.assertFalse(is_ole)
def test_isOleFile_true(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
# Act
is_ole = OleFileIO.isOleFile(ole_file)
# Assert
self.assertTrue(is_ole)
def test_exists_worddocument(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
exists = ole.exists('worddocument')
# Assert
self.assertTrue(exists)
ole.close()
def test_exists_no_vba_macros(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
exists = ole.exists('macros/vba')
# Assert
self.assertFalse(exists)
ole.close()
def test_get_type(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
type = ole.get_type('worddocument')
# Assert
self.assertEqual(type, OleFileIO.STGTY_STREAM)
ole.close()
def test_get_size(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
size = ole.get_size('worddocument')
# Assert
self.assertGreater(size, 0)
ole.close()
def test_get_rootentry_name(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
root = ole.get_rootentry_name()
# Assert
self.assertEqual(root, "Root Entry")
ole.close()
def test_meta(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
meta = ole.get_metadata()
# Assert
self.assertEqual(meta.author, b"Laurence Ipsum")
self.assertEqual(meta.num_pages, 1)
ole.close()
def test_gettimes(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
root_entry = ole.direntries[0]
# Act
ctime = root_entry.getctime()
mtime = root_entry.getmtime()
# Assert
self.assertIsInstance(ctime, type(None))
self.assertIsInstance(mtime, datetime.datetime)
self.assertEqual(ctime, None)
self.assertEqual(mtime.year, 2014)
ole.close()
def test_listdir(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
dirlist = ole.listdir()
# Assert
self.assertIn(['WordDocument'], dirlist)
ole.close()
def test_debug(self):
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
meta = ole.get_metadata()
# Act
OleFileIO.set_debug_mode(True)
ole.dumpdirectory()
meta.dump()
OleFileIO.set_debug_mode(False)
ole.dumpdirectory()
meta.dump()
# Assert
# No assert, just check they run ok
ole.close()
def test_isOleFile_true(): if __name__ == '__main__':
# Arrange unittest.main()
ole_file = "Tests/images/test-ole-file.doc"
# Act
is_ole = OleFileIO.isOleFile(ole_file)
# Assert
assert_true(is_ole)
def test_exists_worddocument():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
exists = ole.exists('worddocument')
# Assert
assert_true(exists)
ole.close()
def test_exists_no_vba_macros():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
exists = ole.exists('macros/vba')
# Assert
assert_false(exists)
ole.close()
def test_get_type():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
type = ole.get_type('worddocument')
# Assert
assert_equal(type, OleFileIO.STGTY_STREAM)
ole.close()
def test_get_size():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
size = ole.get_size('worddocument')
# Assert
assert_greater(size, 0)
ole.close()
def test_get_rootentry_name():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
root = ole.get_rootentry_name()
# Assert
assert_equal(root, "Root Entry")
ole.close()
def test_meta():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
meta = ole.get_metadata()
# Assert
assert_equal(meta.author, b"Laurence Ipsum")
assert_equal(meta.num_pages, 1)
ole.close()
def test_gettimes():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
root_entry = ole.direntries[0]
# Act
ctime = root_entry.getctime()
mtime = root_entry.getmtime()
# Assert
assert_is_instance(ctime, type(None))
assert_is_instance(mtime, datetime.datetime)
assert_equal(ctime, None)
assert_equal(mtime.year, 2014)
ole.close()
def test_listdir():
# Arrange
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
# Act
dirlist = ole.listdir()
# Assert
assert_in(['WordDocument'], dirlist)
ole.close()
def test_debug():
# Arrange
print("ignore_all_except_last_line")
ole_file = "Tests/images/test-ole-file.doc"
ole = OleFileIO.OleFileIO(ole_file)
meta = ole.get_metadata()
# Act
OleFileIO.set_debug_mode(True)
ole.dumpdirectory()
meta.dump()
OleFileIO.set_debug_mode(False)
ole.dumpdirectory()
meta.dump()
# Assert
# No assert, just check they run ok
print("ok")
ole.close()
# End of file # End of file

View File

@ -1,70 +1,73 @@
from tester import * from helper import unittest, PillowTestCase, tearDownModule
from PIL import Image from PIL import Image
def helper_test_pickle_file(pickle, protocol=0): class TestPickle(PillowTestCase):
im = Image.open('Images/lena.jpg')
filename = tempfile('temp.pkl')
# Act def helper_pickle_file(self, pickle, protocol=0):
with open(filename, 'wb') as f: im = Image.open('Images/lena.jpg')
pickle.dump(im, f, protocol) filename = self.tempfile('temp.pkl')
with open(filename, 'rb') as f:
loaded_im = pickle.load(f)
# Assert # Act
assert_image_completely_equal(im, loaded_im) with open(filename, 'wb') as f:
pickle.dump(im, f, protocol)
with open(filename, 'rb') as f:
loaded_im = pickle.load(f)
# Assert
self.assertEqual(im, loaded_im)
def helper_pickle_string(
self, pickle, protocol=0, file='Images/lena.jpg'):
im = Image.open(file)
# Act
dumped_string = pickle.dumps(im, protocol)
loaded_im = pickle.loads(dumped_string)
# Assert
self.assertEqual(im, loaded_im)
def test_pickle_image(self):
# Arrange
import pickle
# Act / Assert
for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
self.helper_pickle_string(pickle, protocol)
self.helper_pickle_file(pickle, protocol)
def test_cpickle_image(self):
# Arrange
try:
import cPickle
except ImportError:
return
# Act / Assert
for protocol in range(0, cPickle.HIGHEST_PROTOCOL + 1):
self.helper_pickle_string(cPickle, protocol)
self.helper_pickle_file(cPickle, protocol)
def test_pickle_p_mode(self):
# Arrange
import pickle
# Act / Assert
for file in [
"Tests/images/test-card.png",
"Tests/images/zero_bb.png",
"Tests/images/zero_bb_scale2.png",
"Tests/images/non_zero_bb.png",
"Tests/images/non_zero_bb_scale2.png",
"Tests/images/p_trns_single.png",
"Tests/images/pil123p.png"
]:
self.helper_pickle_string(pickle, file=file)
def helper_test_pickle_string(pickle, protocol=0, file='Images/lena.jpg'): if __name__ == '__main__':
im = Image.open(file) unittest.main()
# Act
dumped_string = pickle.dumps(im, protocol)
loaded_im = pickle.loads(dumped_string)
# Assert
assert_image_completely_equal(im, loaded_im)
def test_pickle_image():
# Arrange
import pickle
# Act / Assert
for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
helper_test_pickle_string(pickle, protocol)
helper_test_pickle_file(pickle, protocol)
def test_cpickle_image():
# Arrange
try:
import cPickle
except ImportError:
return
# Act / Assert
for protocol in range(0, cPickle.HIGHEST_PROTOCOL + 1):
helper_test_pickle_string(cPickle, protocol)
helper_test_pickle_file(cPickle, protocol)
def test_pickle_p_mode():
# Arrange
import pickle
# Act / Assert
for file in [
"Tests/images/test-card.png",
"Tests/images/zero_bb.png",
"Tests/images/zero_bb_scale2.png",
"Tests/images/non_zero_bb.png",
"Tests/images/non_zero_bb_scale2.png",
"Tests/images/p_trns_single.png",
"Tests/images/pil123p.png"
]:
helper_test_pickle_string(pickle, file=file)
# End of file # End of file