Skip to content

Instantly share code, notes, and snippets.

@theonlypwner
Last active August 25, 2023 09:58

Revisions

  1. theonlypwner revised this gist Feb 26, 2016. 1 changed file with 13 additions and 0 deletions.
    13 changes: 13 additions & 0 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -99,6 +99,19 @@ def rPNG():
    filtermethod = 0 # adaptive (only supported method)
    interlaced = 0 # no

    maxEntropyBits = DEPTH * IMAGE_W * IMAGE_H
    print("Projected (maximum) entropy: {0} bits ({1} bytes)".format(
    maxEntropyBits,
    (maxEntropyBits + 7) >> 3,
    ))
    approxFileSize = (DEPTH * (IMAGE_W + 1) * IMAGE_H * BLOCK_W * BLOCK_H) >> 10 # approx / 1032
    approxFileSize += 64 # FIXME
    approxFileSize += maxEntropyBits
    print("Estimated file size: {0} bits ({1} bytes)".format(
    approxFileSize,
    (approxFileSize + 7) >> 3,
    ))

    if DEPTH == 1:
    bytesPerRow = (DEPTH * IMAGE_W + 7) >> 3
    else:
  2. theonlypwner revised this gist Feb 26, 2016. 1 changed file with 9 additions and 4 deletions.
    13 changes: 9 additions & 4 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -39,6 +39,8 @@ def B(x):
    def I4(x):
    return struct.pack(">I", x & 0xFFFFFFFF)

    zero16KiB = b"\0" * 16383

    class CompressedPixelWriter:
    compressor = zlib.compressobj(9) # max compression
    out = lambda: None
    @@ -56,11 +58,14 @@ def writeRaw(self, b):
    def write(self, b):
    self.writeRaw(self.compressor.compress(b))

    # memory-optimized write() for many zero bytes
    # improved write() for many zero bytes
    def writez(self, num):
    for i in range(num):
    self.out(self.compressor.compress(b"\0"))
    self.crc32 = zlib.crc32(b"\0", self.crc32)
    for i in range(num >> 14):
    self.out(self.compressor.compress(zero16KiB))
    self.crc32 = zlib.crc32(zero16KiB, self.crc32)
    num &= 0x3FFF
    self.out(self.compressor.compress(b"\0" * num))
    self.crc32 = zlib.crc32(b"\0" * num, self.crc32)
    self.length += num

    def writePixels(self):
  3. theonlypwner revised this gist Feb 26, 2016. 1 changed file with 13 additions and 16 deletions.
    29 changes: 13 additions & 16 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -78,7 +78,9 @@ def rPNG():
    height = IMAGE_H * BLOCK_H
    bitdepth = 8 # [bit/sample]
    if DEPTH == 1:
    # bitdepth = 1 # TODO
    bitdepth = 1
    if BLOCK_W > 1:
    raise NotImplementedError("For bit depth of 1, only blocks of width 1 are supported")
    colortype = 0
    elif DEPTH == 8:
    colortype = 0
    @@ -93,23 +95,18 @@ def rPNG():
    interlaced = 0 # no

    if DEPTH == 1:
    bytesPerPixel = 1
    def imageFilter(b):
    b = bytearray(b)
    for i in range(len(b)):
    b[i] = -(b[i] & 0x1) & 0xFF
    return bytes(b)
    bytesPerRow = (DEPTH * IMAGE_W + 7) >> 3
    else:
    bytesPerPixel = DEPTH >> 3
    imageFilter = bytes
    if BLOCK_W > 1:
    pixelPadding = bytesPerPixel * (BLOCK_W - 1)
    bytesPerRow = bytesPerPixel * IMAGE_W
    rowPadding = bytesPerRow * BLOCK_W

    class RandomPixelWriter(CompressedPixelWriter):

    def writePixels(self):
    # Bad practice: using globals
    # - BLOCK_W, BLOCK_H, IMAGE_W, IMAGE_H (sort of OK)
    # - bytesPerPixel
    # - imageFilter
    # This method uses globals, which is probably bad...

    for y in range(IMAGE_H):
    # Write scanline
    @@ -119,16 +116,16 @@ def writePixels(self):
    for x in range(IMAGE_W):
    # There is no need to subtract from prev,
    # because random differences are still random.
    self.write(imageFilter(urandom(bytesPerPixel)))
    self.writez(bytesPerPixel * (BLOCK_W - 1))
    self.write(urandom(bytesPerPixel))
    self.writez(pixelPadding)
    else:
    self.write(b"\x00") # no PNG filter
    self.write(imageFilter(urandom(bytesPerPixel * IMAGE_W)))
    self.write(urandom(bytesPerRow))

    # Repeat previous scanline, at least one time, if needed
    for i in range(1, BLOCK_H):
    self.write(b"\x02") # Up filter
    self.writez(bytesPerPixel * IMAGE_W * BLOCK_W)
    self.writez(rowPadding)

    with open(OUTPUT_FILE, "wb") as f:
    # Signature
  4. theonlypwner revised this gist Feb 24, 2016. 1 changed file with 23 additions and 27 deletions.
    50 changes: 23 additions & 27 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -21,13 +21,12 @@
    OUTPUT_FILE = "r.png" # Do I really need to explain this?
    BLOCK_W, BLOCK_H = 8, 8 # block size [pixels]
    IMAGE_W, IMAGE_H = 240, 135 # image size [blocks]
    DEPTH = 3
    DEPTH = 24
    # Color depth [bytes/pixel]
    # 1 Grayscale
    # 3 RGB
    # 4 RGBA
    # -1 Black and White
    # -3 Black and White (as RGB)
    # 1 Black and White
    # 8 Grayscale
    # 24 RGB
    # 32 RGBA

    # Script
    from os import urandom
    @@ -57,7 +56,7 @@ def writeRaw(self, b):
    def write(self, b):
    self.writeRaw(self.compressor.compress(b))

    # optimized write() for many zero bytes
    # memory-optimized write() for many zero bytes
    def writez(self, num):
    for i in range(num):
    self.out(self.compressor.compress(b"\0"))
    @@ -78,61 +77,58 @@ def rPNG():
    width = IMAGE_W * BLOCK_W
    height = IMAGE_H * BLOCK_H
    bitdepth = 8 # [bit/sample]
    if DEPTH == 1 or DEPTH == -1:
    if DEPTH == 1:
    # bitdepth = 1 # TODO
    colortype = 0
    elif DEPTH == 3 or DEPTH == -3:
    elif DEPTH == 8:
    colortype = 0
    elif DEPTH == 24:
    colortype = 2
    elif DEPTH == 4:
    elif DEPTH == 32:
    colortype = 6
    else:
    raise NotImplementedError("Unsupported color depth " + DEPTH)
    raise NotImplementedError("Unsupported color depth {0}".format(DEPTH))
    compresstype = 0 # zlib (only supported method)
    filtermethod = 0 # adaptive (only supported method)
    interlaced = 0 # no

    if DEPTH < 1:
    bitsPerPixel = 1
    if DEPTH == 1:
    bytesPerPixel = 1
    def imageFilter(b):
    b = bytearray(b)
    for i in range(len(b)):
    b[i] = -(b[i] & 0x1) & 0xFF
    return bytes(b)
    BLOCK_W *= -DEPTH
    else:
    bitsPerPixel = DEPTH
    bytesPerPixel = DEPTH >> 3
    imageFilter = bytes

    class RandomPixelWriter(CompressedPixelWriter):

    def writePixels(self):
    # Bad practice: using globals
    # - BLOCK_W, BLOCK_H, IMAGE_W, IMAGE_H (sort of OK)
    # - bitsPerPixel
    # - bytesPerPixel
    # - imageFilter

    if BLOCK_H > 1:
    repeatPrior = bytearray(1 + bitsPerPixel * IMAGE_W * BLOCK_W)
    repeatPrior[0] = 2 # Up filter
    #repeatPrior *= (BLOCK_H - 1)
    repeatPrior = bytes(repeatPrior)

    for y in range(IMAGE_H):
    # Write scanline
    if BLOCK_W > 1:
    self.write(b"\x01") # Sub
    #prev = bytearray(bitsPerPixel)
    #prev = bytearray(bytesPerPixel)
    for x in range(IMAGE_W):
    # There is no need to subtract from prev,
    # because random differences are still random.
    self.write(imageFilter(urandom(bitsPerPixel)))
    self.writez(bitsPerPixel * (BLOCK_W - 1))
    self.write(imageFilter(urandom(bytesPerPixel)))
    self.writez(bytesPerPixel * (BLOCK_W - 1))
    else:
    self.write(b"\x00") # no PNG filter
    self.write(imageFilter(urandom(bitsPerPixel * IMAGE_W)))
    self.write(imageFilter(urandom(bytesPerPixel * IMAGE_W)))

    # Repeat previous scanline, at least one time, if needed
    for i in range(1, BLOCK_H):
    self.write(repeatPrior)
    self.write(b"\x02") # Up filter
    self.writez(bytesPerPixel * IMAGE_W * BLOCK_W)

    with open(OUTPUT_FILE, "wb") as f:
    # Signature
  5. theonlypwner revised this gist Feb 24, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion randompng.py
    Original file line number Diff line number Diff line change
    @@ -86,7 +86,7 @@ def rPNG():
    colortype = 6
    else:
    raise NotImplementedError("Unsupported color depth " + DEPTH)
    compresstype = 0 # DEFLATE (only supported method)
    compresstype = 0 # zlib (only supported method)
    filtermethod = 0 # adaptive (only supported method)
    interlaced = 0 # no

  6. theonlypwner renamed this gist Feb 23, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes
  7. theonlypwner renamed this gist Feb 23, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes
  8. theonlypwner revised this gist Feb 23, 2016. 1 changed file with 0 additions and 0 deletions.
    Binary file added r.png
    Loading
    Sorry, something went wrong. Reload?
    Sorry, we cannot display this file.
    Sorry, this file is invalid so it cannot be displayed.
  9. theonlypwner revised this gist Feb 23, 2016. 1 changed file with 75 additions and 37 deletions.
    112 changes: 75 additions & 37 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -19,8 +19,8 @@
    # Settings

    OUTPUT_FILE = "r.png" # Do I really need to explain this?
    BLOCK_W, BLOCK_H = 1, 1 # block size [pixels]
    IMAGE_W, IMAGE_H = 1920, 1080 # image size [blocks]
    BLOCK_W, BLOCK_H = 8, 8 # block size [pixels]
    IMAGE_W, IMAGE_H = 240, 135 # image size [blocks]
    DEPTH = 3
    # Color depth [bytes/pixel]
    # 1 Grayscale
    @@ -40,6 +40,38 @@ def B(x):
    def I4(x):
    return struct.pack(">I", x & 0xFFFFFFFF)

    class CompressedPixelWriter:
    compressor = zlib.compressobj(9) # max compression
    out = lambda: None
    length = 0
    crc32 = 0x35AF061E # crc32("IDAT")

    def __init__(self, out):
    self.out = out

    def writeRaw(self, b):
    self.out(b)
    self.length += len(b)
    self.crc32 = zlib.crc32(b, self.crc32)

    def write(self, b):
    self.writeRaw(self.compressor.compress(b))

    # optimized write() for many zero bytes
    def writez(self, num):
    for i in range(num):
    self.out(self.compressor.compress(b"\0"))
    self.crc32 = zlib.crc32(b"\0", self.crc32)
    self.length += num

    def writePixels(self):
    # Empty image data
    pass

    def finalize(self):
    self.writePixels()
    self.writeRaw(self.compressor.flush())

    def rPNG():
    global BLOCK_W

    @@ -70,33 +102,37 @@ def imageFilter(b):
    bitsPerPixel = DEPTH
    imageFilter = bytes

    pixels = bytearray()
    if BLOCK_H > 1:
    repeatPrior = bytearray(1 + bitsPerPixel * IMAGE_W * BLOCK_W)
    repeatPrior[0] = 2 # Up filter
    repeatPrior *= (BLOCK_H - 1)
    if BLOCK_W > 1:
    repeatLeft = bytearray(bitsPerPixel * (BLOCK_W - 1))

    for y in range(IMAGE_H):
    # Write scanline
    if BLOCK_W > 1:
    pixels.append(1) # Sub
    #prev = bytearray(bitsPerPixel)
    for x in range(IMAGE_W):
    # There is no need to subtract from prev,
    # because random differences are still random.
    pixels.extend(imageFilter(urandom(bitsPerPixel)))
    pixels.extend(repeatLeft)
    else:
    pixels.append(0) # no PNG filter
    pixels.extend(imageFilter(urandom(bitsPerPixel * IMAGE_W)))

    # Repeat previous scanline, at least one time, if needed
    if BLOCK_H > 1:
    pixels.extend(repeatPrior)

    pixels = bytes(pixels)
    class RandomPixelWriter(CompressedPixelWriter):

    def writePixels(self):
    # Bad practice: using globals
    # - BLOCK_W, BLOCK_H, IMAGE_W, IMAGE_H (sort of OK)
    # - bitsPerPixel
    # - imageFilter

    if BLOCK_H > 1:
    repeatPrior = bytearray(1 + bitsPerPixel * IMAGE_W * BLOCK_W)
    repeatPrior[0] = 2 # Up filter
    #repeatPrior *= (BLOCK_H - 1)
    repeatPrior = bytes(repeatPrior)

    for y in range(IMAGE_H):
    # Write scanline
    if BLOCK_W > 1:
    self.write(b"\x01") # Sub
    #prev = bytearray(bitsPerPixel)
    for x in range(IMAGE_W):
    # There is no need to subtract from prev,
    # because random differences are still random.
    self.write(imageFilter(urandom(bitsPerPixel)))
    self.writez(bitsPerPixel * (BLOCK_W - 1))
    else:
    self.write(b"\x00") # no PNG filter
    self.write(imageFilter(urandom(bitsPerPixel * IMAGE_W)))

    # Repeat previous scanline, at least one time, if needed
    for i in range(1, BLOCK_H):
    self.write(repeatPrior)

    with open(OUTPUT_FILE, "wb") as f:
    # Signature
    @@ -111,17 +147,19 @@ def imageFilter(b):
    + B(filtermethod) \
    + B(interlaced)

    f.write(I4(len(IHDR) - 4))
    f.write(I4(len(IHDR) - 4)) # 13
    f.write(IHDR)
    f.write(I4(zlib.crc32(IHDR)))
    # IDAT
    compressor = zlib.compressobj(9) # max compression
    IDAT = b"IDAT" + \
    compressor.compress(pixels) + \
    compressor.flush()
    f.write(I4(len(IDAT) - 4))
    f.write(IDAT)
    f.write(I4(zlib.crc32(IDAT)))
    IDAT_len_offset = f.tell() # 33
    f.write(b"\0\0\0\0IDAT")
    pWriter = RandomPixelWriter(f.write)
    pWriter.finalize()
    f.write(I4(pWriter.crc32))
    # Fix length
    f.seek(IDAT_len_offset)
    f.write(I4(pWriter.length))
    f.seek(0, 2) # to end
    # IEND
    # 0x00000000 + "IEND" + CRC32("IEND")
    f.write(b"\0\0\0\0IEND\xae\x42\x60\x82")
  10. theonlypwner revised this gist Feb 22, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion randompng.py
    Original file line number Diff line number Diff line change
    @@ -78,7 +78,7 @@ def imageFilter(b):
    if BLOCK_W > 1:
    repeatLeft = bytearray(bitsPerPixel * (BLOCK_W - 1))

    for y in range(IMAGE_W):
    for y in range(IMAGE_H):
    # Write scanline
    if BLOCK_W > 1:
    pixels.append(1) # Sub
  11. theonlypwner revised this gist Feb 22, 2016. 1 changed file with 5 additions and 4 deletions.
    9 changes: 5 additions & 4 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -68,12 +68,13 @@ def imageFilter(b):
    BLOCK_W *= -DEPTH
    else:
    bitsPerPixel = DEPTH
    imageFilter = lambda b: bytes(b)
    imageFilter = bytes

    pixels = bytearray()
    if BLOCK_H > 1:
    repeatPrior = bytearray(1 + bitsPerPixel * IMAGE_W * BLOCK_W)
    repeatPrior[0] = 2 # Up filter
    repeatPrior *= (BLOCK_H - 1)
    if BLOCK_W > 1:
    repeatLeft = bytearray(bitsPerPixel * (BLOCK_W - 1))

    @@ -83,16 +84,16 @@ def imageFilter(b):
    pixels.append(1) # Sub
    #prev = bytearray(bitsPerPixel)
    for x in range(IMAGE_W):
    # We don't need to sub from prev
    # There is no need to subtract from prev,
    # because random differences are still random.
    pixels.extend(imageFilter(urandom(bitsPerPixel)))
    pixels.extend(repeatLeft)
    else:
    pixels.append(0) # no PNG filter
    pixels.extend(imageFilter(urandom(bitsPerPixel * IMAGE_W)))

    # Repeat previous scanline when needed
    for i in range(1, BLOCK_H):
    # Repeat previous scanline, at least one time, if needed
    if BLOCK_H > 1:
    pixels.extend(repeatPrior)

    pixels = bytes(pixels)
  12. theonlypwner revised this gist Feb 22, 2016. 1 changed file with 23 additions and 8 deletions.
    31 changes: 23 additions & 8 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -68,18 +68,33 @@ def imageFilter(b):
    BLOCK_W *= -DEPTH
    else:
    bitsPerPixel = DEPTH
    imageFilter = lambda x: x
    imageFilter = lambda b: bytes(b)

    pixels = bytearray()
    if BLOCK_H > 1:
    repeatPrior = bytearray(1 + bitsPerPixel * IMAGE_W * BLOCK_W)
    repeatPrior[0] = 2 # Up filter
    if BLOCK_W > 1:
    repeatLeft = bytearray(bitsPerPixel * (BLOCK_W - 1))

    for y in range(IMAGE_W):
    row = bytearray()
    row.append(0) # no PNG filter
    if BLOCK_W == 1:
    row.extend(imageFilter(urandom(bitsPerPixel * IMAGE_W)))
    else:
    # Write scanline
    if BLOCK_W > 1:
    pixels.append(1) # Sub
    #prev = bytearray(bitsPerPixel)
    for x in range(IMAGE_W):
    row.extend(imageFilter(urandom(bitsPerPixel)) * BLOCK_W)
    pixels.extend(row * BLOCK_H)
    # We don't need to sub from prev
    # because random differences are still random.
    pixels.extend(imageFilter(urandom(bitsPerPixel)))
    pixels.extend(repeatLeft)
    else:
    pixels.append(0) # no PNG filter
    pixels.extend(imageFilter(urandom(bitsPerPixel * IMAGE_W)))

    # Repeat previous scanline when needed
    for i in range(1, BLOCK_H):
    pixels.extend(repeatPrior)

    pixels = bytes(pixels)

    with open(OUTPUT_FILE, "wb") as f:
  13. theonlypwner created this gist Feb 21, 2016.
    114 changes: 114 additions & 0 deletions randompng.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,114 @@
    #!/usr/bin/env python
    # Random PNG generator
    __copyright__ = "Copyright (C) 2016 Victor Zheng"
    __licence__ = "GNU GPL v3"

    # This program is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.

    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    # GNU General Public License for more details.

    # You should have received a copy of the GNU General Public License
    # along with this program. If not, see <http://www.gnu.org/licenses/>.

    # Settings

    OUTPUT_FILE = "r.png" # Do I really need to explain this?
    BLOCK_W, BLOCK_H = 1, 1 # block size [pixels]
    IMAGE_W, IMAGE_H = 1920, 1080 # image size [blocks]
    DEPTH = 3
    # Color depth [bytes/pixel]
    # 1 Grayscale
    # 3 RGB
    # 4 RGBA
    # -1 Black and White
    # -3 Black and White (as RGB)

    # Script
    from os import urandom
    import struct
    import zlib

    def B(x):
    return struct.pack(">B", x & 0xFF)

    def I4(x):
    return struct.pack(">I", x & 0xFFFFFFFF)

    def rPNG():
    global BLOCK_W

    width = IMAGE_W * BLOCK_W
    height = IMAGE_H * BLOCK_H
    bitdepth = 8 # [bit/sample]
    if DEPTH == 1 or DEPTH == -1:
    colortype = 0
    elif DEPTH == 3 or DEPTH == -3:
    colortype = 2
    elif DEPTH == 4:
    colortype = 6
    else:
    raise NotImplementedError("Unsupported color depth " + DEPTH)
    compresstype = 0 # DEFLATE (only supported method)
    filtermethod = 0 # adaptive (only supported method)
    interlaced = 0 # no

    if DEPTH < 1:
    bitsPerPixel = 1
    def imageFilter(b):
    b = bytearray(b)
    for i in range(len(b)):
    b[i] = -(b[i] & 0x1) & 0xFF
    return bytes(b)
    BLOCK_W *= -DEPTH
    else:
    bitsPerPixel = DEPTH
    imageFilter = lambda x: x

    pixels = bytearray()
    for y in range(IMAGE_W):
    row = bytearray()
    row.append(0) # no PNG filter
    if BLOCK_W == 1:
    row.extend(imageFilter(urandom(bitsPerPixel * IMAGE_W)))
    else:
    for x in range(IMAGE_W):
    row.extend(imageFilter(urandom(bitsPerPixel)) * BLOCK_W)
    pixels.extend(row * BLOCK_H)
    pixels = bytes(pixels)

    with open(OUTPUT_FILE, "wb") as f:
    # Signature
    f.write(b"\x89PNG\r\n\x1A\n")
    # IHDR
    IHDR = b"IHDR" \
    + I4(width) \
    + I4(height) \
    + B(bitdepth) \
    + B(colortype) \
    + B(compresstype) \
    + B(filtermethod) \
    + B(interlaced)

    f.write(I4(len(IHDR) - 4))
    f.write(IHDR)
    f.write(I4(zlib.crc32(IHDR)))
    # IDAT
    compressor = zlib.compressobj(9) # max compression
    IDAT = b"IDAT" + \
    compressor.compress(pixels) + \
    compressor.flush()
    f.write(I4(len(IDAT) - 4))
    f.write(IDAT)
    f.write(I4(zlib.crc32(IDAT)))
    # IEND
    # 0x00000000 + "IEND" + CRC32("IEND")
    f.write(b"\0\0\0\0IEND\xae\x42\x60\x82")

    if __name__ == '__main__':
    rPNG()