def test_reading_from_png(): # Empty icon icon = Icon() assert icon.image_sizes() == () assert '0 sizes' in repr(icon) # Write images filenames = [None for x in ims] for i in range(len(ims)): if ims[i]: filename = os.path.join(tempdir, 'ico%i.png' % i) with open(filename, 'wb') as f: write_png(ims[i], shapes[i], f) filenames[i] = filename # One image in the icon icon = Icon(filenames[0]) assert icon.image_sizes() == (16, ) assert '1 sizes' in repr(icon) # Four images in the icon icon = Icon(*filenames[:4]) assert icon.image_sizes() == (16, 32, 48, 64) assert '4 sizes' in repr(icon) # Two image in the icon icon = Icon(filenames[1], filenames[3]) assert icon.image_sizes() == (32, 64) assert '2 sizes' in repr(icon) # Add images icon.read(filenames[2]) assert icon.image_sizes() == (32, 48, 64) assert '3 sizes' in repr(icon)
def test_writing(): # Get bytes b0 = write_png(im0, shape0) b1 = write_png(im1, shape1) b2 = write_png(im2, shape2) b3 = write_png(im3, shape3) b4 = write_png(im4, shape4) blobs = b0, b1, b2, b3, b4 # Write to disk (also for visual inspection) for i in range(5): filename = os.path.join(tempdir, 'test%i.png' % i) with open(filename, 'wb') as f: f.write(blobs[i]) print('wrote PNG test images to', tempdir) assert len(b1) < len(b4) # because all zeros are easier to compress # Check that providing file object yields same result with open(filename+'.check', 'wb') as f: write_png(im4, shape4, f) bb1 = open(filename, 'rb').read() bb2 = open(filename+'.check', 'rb').read() assert len(bb1) == len(bb2) assert bb1 == bb2 # Check bytesarray b4_check = write_png(bytearray(im4), shape4) assert b4_check == b4 # Test shape with singleton dim b1_check = write_png(im1, (shape1[0], shape1[1], 1)) assert b1_check == b1
def test_with_numpy(): if np is None: skip('Numpy not available') im = np.random.normal(100, 50, (100, 100, 1)).astype(np.float32) with raises(TypeError): # need uint8 write_png(im) im = np.ones((100, 100, 1), np.uint8) * (7*16+7) blob = write_png(im) assert blob == write_png(im0, shape0) im = np.random.normal(100, 50, (100, 100)).astype(np.uint8) blob = write_png(im) im_bytes, shape = read_png(blob) assert isinstance(im_bytes, (bytearray, bytes)) im_check = np.frombuffer(im_bytes, 'uint8').reshape(shape) assert im_check.shape == im.shape + (3, ) for i in range(3): assert (im_check[:,:,i] == im).all()
def test_writing_failures(): with raises(ValueError): write_png([1, 2, 3, 4], (2, 2)) with raises(ValueError): write_png(b'x'*10) with raises(ValueError): write_png(b'x'*10, (3, 3)) write_png(b'x'*12, (2, 2, 3)) with raises(ValueError): write_png(b'x'*8, (2, 2, 2)) with raises(ValueError): write_png(b'x'*20, (2, 2, 5)) with raises(ValueError): write_png(b'x'*13, (2, 2, 3))