strip_png_metadata.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #!/usr/bin/env python3
  2. """Strip metadata chunks from PNG files, in place, using only the standard library.
  3. Allowlist, not blocklist: only these chunks survive.
  4. IHDR PLTE IDAT IEND the image itself
  5. tRNS transparency (palette or color-key alpha)
  6. gAMA cHRM sRGB the color description a browser screenshot carries
  7. Everything else is dropped: text (tEXt, zTXt, iTXt), EXIF (eXIf), timestamps
  8. (tIME), physical size (pHYs), background (bKGD), histogram, suggested palette,
  9. private chunks, and the embedded ICC profile (iCCP). iCCP is removed on
  10. purpose: a profile carries free text (description, copyright, device and
  11. software names) that can identify a machine, and sRGB plus gAMA/cHRM describe
  12. what a browser screenshot needs; a viewer with no profile assumes sRGB. If a
  13. picture's colors matter beyond that, check it by eye after stripping.
  14. The file is validated as it is read: a good signature, an IHDR first, every
  15. CRC correct, exactly one IEND which is the last chunk with nothing after it,
  16. and every chunk inside the file. APNG (acTL, fcTL, fdAT) is refused, because
  17. dropping those chunks would silently turn an animation into one still frame.
  18. A file that fails any check is reported and left untouched.
  19. Usage: python scripts/strip_png_metadata.py FILE.png [FILE.png ...]
  20. python scripts/strip_png_metadata.py --check FILE.png ... (exit 1 if any would change or is invalid)
  21. """
  22. from __future__ import annotations
  23. import struct
  24. import sys
  25. import zlib
  26. from pathlib import Path
  27. SIGNATURE = b"\x89PNG\r\n\x1a\n"
  28. KEEP = frozenset({b"IHDR", b"PLTE", b"tRNS", b"IDAT", b"IEND", b"gAMA", b"cHRM", b"sRGB"})
  29. APNG = frozenset({b"acTL", b"fcTL", b"fdAT"})
  30. MAX_CHUNK = 2**31 - 1
  31. class PngError(ValueError):
  32. """The file is not a well-formed, supported PNG."""
  33. def chunks(data: bytes):
  34. """Yield (type, raw bytes with length and CRC) for each chunk, validating the structure."""
  35. if not data.startswith(SIGNATURE):
  36. raise PngError("not a PNG (bad signature)")
  37. pos = len(SIGNATURE)
  38. seen_iend = False
  39. first = True
  40. while pos < len(data):
  41. if seen_iend:
  42. raise PngError("data after IEND")
  43. if pos + 8 > len(data):
  44. raise PngError("truncated chunk header")
  45. (length,) = struct.unpack(">I", data[pos : pos + 4])
  46. kind = data[pos + 4 : pos + 8]
  47. if length > MAX_CHUNK:
  48. raise PngError(f"chunk {kind!r} has an impossible length")
  49. end = pos + 12 + length
  50. if end > len(data):
  51. raise PngError(f"truncated chunk {kind!r}")
  52. body = data[pos + 8 : pos + 8 + length]
  53. (crc,) = struct.unpack(">I", data[end - 4 : end])
  54. if zlib.crc32(kind + body) & 0xFFFFFFFF != crc:
  55. raise PngError(f"bad CRC in chunk {kind!r}")
  56. if kind in APNG:
  57. raise PngError("APNG (animated PNG) is not supported")
  58. if first and (kind != b"IHDR" or length != 13):
  59. raise PngError("first chunk is not a 13-byte IHDR")
  60. first = False
  61. if kind == b"IEND":
  62. if length != 0:
  63. raise PngError("IEND is not empty")
  64. seen_iend = True
  65. yield kind, data[pos:end]
  66. pos = end
  67. if not seen_iend:
  68. raise PngError("missing IEND")
  69. def chunk_types(data: bytes) -> list[bytes]:
  70. return [kind for kind, _ in chunks(data)]
  71. def strip(data: bytes) -> bytes:
  72. kept = [raw for kind, raw in chunks(data) if kind in KEEP]
  73. return SIGNATURE + b"".join(kept)
  74. def main(argv: list[str]) -> int:
  75. check = "--check" in argv
  76. files = [a for a in argv if a != "--check"]
  77. if not files:
  78. print(__doc__, file=sys.stderr)
  79. return 2
  80. status = 0
  81. for name in files:
  82. path = Path(name)
  83. try:
  84. data = path.read_bytes()
  85. clean = strip(data)
  86. except (PngError, OSError) as err:
  87. print(f"{name}: {err}", file=sys.stderr)
  88. status = 1
  89. continue
  90. if clean != data:
  91. if check:
  92. print(f"{name}: has metadata chunks")
  93. status = 1
  94. else:
  95. path.write_bytes(clean)
  96. print(f"{name}: stripped {len(data) - len(clean)} bytes")
  97. return status
  98. if __name__ == "__main__":
  99. sys.exit(main(sys.argv[1:]))