# LZW fixtures (tools/fixtures.py): code streams written by reference encoders, with the data they encode. # tests/gen/lzw.luau { gif = { { name, min, codes, data } }, tiff = { { name, codes, data } } } # gif: Pillow's GIF writer (its own LZW), the image data sub-blocks joined; data = the palette indexes # tiff: libtiff's LZW (Pillow compression="tiff_lzw"), one strip; data = the raw 8-bit samples import struct CODE = r''' import io, random, struct, sys from PIL import Image rng = random.Random(7) def img(w, h, kind, ncol): px = bytearray() for y in range(h): for x in range(w): if kind == "noise": px.append(rng.randrange(ncol)) elif kind == "flat": px.append(3 % ncol) else: px.append(((x // 3) ^ (y // 5)) % ncol if rng.random() < 0.97 else rng.randrange(ncol)) return bytes(px) out = [] for (w, h, kind, ncol) in ((1, 1, "noise", 2), (16, 16, "noise", 2), (64, 48, "pattern", 4), (64, 48, "noise", 16), (300, 200, "pattern", 256), (300, 200, "noise", 256), (256, 200, "flat", 256), (97, 3, "noise", 128)): data = img(w, h, kind, ncol) im = Image.frombytes("P", (w, h), data) im.putpalette(bytes(range(256)) * 3) b = io.BytesIO(); im.save(b, "GIF", optimize=False, interlace=False); g = b.getvalue() # walk to the image descriptor p = 13 + (3 << ((g[10] & 7) + 1) if g[10] & 0x80 else 0) while g[p] != 0x2C: p += 2 while g[p]: p += g[p] + 1 p += 1 flags = g[p + 9]; p += 10 if flags & 0x80: p += 3 << ((flags & 7) + 1) mn = g[p]; p += 1; codes = bytearray() while g[p]: codes += g[p + 1:p + 1 + g[p]]; p += g[p] + 1 # Pillow may reduce the palette: decode its own image back for the indexes back = Image.open(io.BytesIO(g)); back.load() out.append(("gif", "%dx%d-%s-%d" % (w, h, kind, ncol), mn, bytes(codes), back.tobytes())) t = io.BytesIO() Image.frombytes("L", (w, h), data).save(t, "TIFF", compression="tiff_lzw", rowsperstrip=h) tb = t.getvalue() le = tb[:2] == b"II"; E = "<" if le else ">" ifd = struct.unpack(E + "I", tb[4:8])[0]; n = struct.unpack(E + "H", tb[ifd:ifd + 2])[0] tags = {} for i in range(n): tag, typ, cnt, val = struct.unpack(E + "HHII", tb[ifd + 2 + i * 12: ifd + 14 + i * 12]) if typ == 3 and cnt == 1: val = struct.unpack(E + "H", tb[ifd + 10 + i * 12: ifd + 12 + i * 12])[0] tags[tag] = (val, cnt) assert tags[259][0] == 5 and tags[273][1] == 1, "one LZW strip" off, cnt = tags[273][0], tags[279][0] out.append(("tiff", "%dx%d-%s-%d" % (w, h, kind, ncol), 8, tb[off:off + cnt], data)) for kind, name, mn, codes, data in out: sys.stdout.buffer.write(struct.pack("<4sB", kind.ljust(4).encode(), len(name)) + name.encode() + struct.pack("