"""Write the BMP shapes ImageMagick will not emit. ImageMagick covers the ordinary files (1/4/8-bit palettes, RLE8, 24-bit), but it has no switch for a 16-bit bitfield file, a top-down row order, a 32-bit file with an alpha channel, or the 12-byte OS/2 header -- all of which are shapes a decoder meets in the wild. Each is written here from a raw RGBA dump so the pixels are the same picture as the rest of the corpus. """ import struct import sys out, raw, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]) rgba = open(raw, "rb").read() rgba_alpha = open(sys.argv[5], "rb").read() def pixel(source, x, y): at = (y * width + x) * 4 return source[at], source[at + 1], source[at + 2], source[at + 3] def rows(top_down, source=None): source = rgba if source is None else source order = range(height) if top_down else range(height - 1, -1, -1) return [[pixel(source, x, y) for x in range(width)] for y in order] def file_header(offset, size): return b"BM" + struct.pack("> 3) << 11) | ((p[1] >> 2) << 5) | (p[2] >> 3))) write("bf565.bmp", info_v3(16, 3), body, masks565) # 16-bit, 5-5-5, the layout BI_RGB implies at this depth (no mask block). body = packed(16, lambda p: struct.pack( "> 3) << 10) | ((p[1] >> 3) << 5) | (p[2] >> 3))) write("rgb555.bmp", info_v3(16, 0), body) # 32-bit with an alpha channel: the fourth mask only has a home in the # BITMAPV4HEADER, whose 108 bytes carry all four masks plus a colour space. body = packed(32, lambda p: bytes([p[2], p[1], p[0], p[3]]), source=rgba_alpha) v4 = struct.pack( "> 4 if x % 2 == 0 else byte & 0x0F) x = 0 while x < w: run = 1 while x + run < w and run < 254 and indices[x + run] == indices[x]: run += 1 if run >= 2: body += bytes([run, indices[x] << 4 | indices[x]]) x += run continue # A literal run needs at least three pixels to be legal; below that # the encoded form is a run of one. end = x while end < w and end - x < 254: same = 1 while end + same < w and indices[end + same] == indices[end]: same += 1 if same >= 3: break end += same count = end - x if count < 3: body += bytes([1, indices[x] << 4]) x += 1 continue nibbles = bytearray() for i in range(0, count, 2): high = indices[x + i] << 4 low = indices[x + i + 1] if i + 1 < count else 0 nibbles.append(high | low) while len(nibbles) % 2: nibbles.append(0) body += bytes([0, count]) + nibbles x = end body += b"\x00\x00" body = body[:-2] + b"\x00\x01" info = struct.pack("