Skip to content

Instantly share code, notes, and snippets.

@emlun
Last active October 10, 2017 10:33
Show Gist options
  • Save emlun/7b8af7f18bdc8cf11d5de8fe129c1878 to your computer and use it in GitHub Desktop.
Save emlun/7b8af7f18bdc8cf11d5de8fe129c1878 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
# Tiny tool for generating valid but nonsensical PNG images of a given file size.
#
# Usage:
#
# $ python pngen.py SIZE_BYTES
#
# Example:
#
# $ python pngen.py 1024 > output.png
#
# This is free and unencumbered software released into the public domain.
# For details see http://unlicense.org/
import sys
from binascii import hexlify, unhexlify
def hexlen(hex):
return len(hex) // 2
prefix = '89504e470d0a1a0a0000000d4948445200000001000000010802000000907753de'
suffix = '0000000c4944415408d763f89fa20d0003f4018f23441fee0000000049454e44ae426082'
wanted_length = int(sys.argv[1])
min_length = hexlen(prefix) + hexlen(suffix) + 4 + 4 + 4
middle_length = wanted_length - min_length
if middle_length < 0:
print("Wanted image size too small: " + str(wanted_length))
print("Minimum output size: " + str(min_length) + " bytes")
sys.exit(1)
middle_type = '6a754e4b'
middle_length_bytes = '%08x' % middle_length
middle_data = '00' * middle_length
middle_crc = '00000000'
middle = middle_length_bytes + middle_type + middle_data + middle_crc
image = unhexlify(prefix + middle + suffix)
sys.stdout.buffer.write(image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment