forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBddf43e8Tahinli2 months ago3186 commits

gen-tiff-shapes.py66 lines, 2.7 KiBHistoryRawDownload
1"""Write the TIFF alpha shapes ImageMagick will not emit.
2
3ImageMagick always tags a TIFF's alpha channel as associated (ExtraSamples 2,
4premultiplied) and ignores ``-define tiff:alpha=unassociated``, so the ordinary
5straight-alpha file -- the common one -- has to be written here. Both files
6carry the same picture with the alpha flattened to 0 or 255, which makes the
7premultiplication lossless and so lets the two decode to identical pixels.
8"""
9
10import struct
11import sys
12
13out, raw, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
14rgba = open(raw, "rb").read()
15
16# Flatten alpha to fully transparent or fully opaque: premultiplying by 0 or 1
17# loses nothing, so the associated file is recoverable exactly.
18body = bytearray()
19for i in range(0, width * height * 4, 4):
20 r, g, b, a = rgba[i : i + 4]
21 body += bytes((r, g, b, 255 if a >= 128 else 0))
22
23
24def tiff(path, extra_samples):
25 """A little-endian, uncompressed, single-strip RGBA file."""
26 pixels = bytearray(body)
27 if extra_samples == 2:
28 for i in range(0, len(pixels), 4):
29 if pixels[i + 3] == 0:
30 pixels[i : i + 3] = b"\x00\x00\x00"
31
32 # The header is 8 bytes, then the strip, then the directory: writing the
33 # pixels first keeps every out-of-line value at a known offset behind it.
34 strip = 8
35 ifd = strip + len(pixels)
36 entries = [
37 (256, 3, 1, width), # ImageWidth
38 (257, 3, 1, height), # ImageLength
39 (258, 3, 4, None), # BitsPerSample, four shorts, out of line
40 (259, 3, 1, 1), # Compression: none
41 (262, 3, 1, 2), # PhotometricInterpretation: RGB
42 (273, 4, 1, strip), # StripOffsets
43 (277, 3, 1, 4), # SamplesPerPixel
44 (278, 3, 1, height), # RowsPerStrip
45 (279, 4, 1, len(pixels)), # StripByteCounts
46 (284, 3, 1, 1), # PlanarConfiguration: chunky
47 (338, 3, 1, extra_samples), # ExtraSamples
48 ]
49 trailing = ifd + 2 + 12 * len(entries) + 4
50
51 directory = struct.pack("<H", len(entries))
52 for tag, kind, count, value in entries:
53 if value is None:
54 directory += struct.pack("<HHII", tag, kind, count, trailing)
55 elif kind == 3:
56 directory += struct.pack("<HHIHH", tag, kind, count, value, 0)
57 else:
58 directory += struct.pack("<HHII", tag, kind, count, value)
59 directory += struct.pack("<I", 0)
60 directory += struct.pack("<4H", 8, 8, 8, 8)
61
62 open(path, "wb").write(b"II\x2a\x00" + struct.pack("<I", ifd) + pixels + directory)
63
64
65tiff(f"{out}/rgba8.tiff", 1)
66tiff(f"{out}/rgba8-assoc.tiff", 2)