Welcome, guest | Sign In | My Account | Store | Cart

This is a simple PNG writing function, intended to be as small as possible. It only supports RGBA 32bit PNGs and the input should be a buffer of rgba bytes.

Tested for python 2 and 3.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def write_png(buf, width, height):
    import zlib, struct
    width_byte_4 = width * 4
    raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in range((height - 1) * width * 4, -1, - width_byte_4))
    def png_pack(png_tag, data):
        chunk_head = png_tag + data
        return struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))
    return b"".join([
        b'\x89PNG\r\n\x1a\n',
        png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
        png_pack(b'IDAT', zlib.compress(raw_data, 9)),
        png_pack(b'IEND', b'')])

1 comment

Wendal 12 years, 3 months ago  # | flag

Can you provide some examples use in Python 2.7 ?

Created by Campbell Barton on Thu, 28 Oct 2010 (MIT)
Python recipes (4591)
Campbell Barton's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks