All notes
Pypng

Examples

PythonHosted.org: pypng.

Writing

Ramp image. A bit like Netpbm’s pgmramp.


import png
f = open('ramp.png', 'wb')      # binary mode is important
w = png.Writer(255, 1, greyscale=True)
w.write(f, [range(256)])
f.close()

Write a bitonal image.


s = ['110010010011',
     '101011010100',
     '110010110101',
     '100010010011']
s = map(lambda x: map(int, x), s)

f = open('png.png', 'wb')
w = png.Writer(len(s[0]), len(s), greyscale=True, bitdepth=1)
w.write(f, s)
f.close()

Write images with a palette.

In a palette, each entry is an RGB triple. If we wanted transparency then we can use RGBA 4-tuples for each palette entry.


palette=[(0x55,0x55,0x55), (0xff,0x99,0x99)]

s = ['110010010011',
     '101011010100',
     '110010110101',
     '100010010011']
s = map(lambda x: map(int, x), s)

f = open('png.png', 'wb')
w = png.Writer(len(s[0]), len(s), palette=palette, bitdepth=1)
w.write(f, s)

Write color images:


p = [(255,0,0, 0,255,0, 0,0,255),
     (128,0,0, 0,128,0, 0,0,128)]
f = open('swatch.png', 'wb')
w = png.Writer(3, 2)
w.write(f, p) ; f.close()