Python で png 画像を自力で生成する(パレット編)

特に何かが難しかったりするわけでもないですが.

from sys import stdout
from struct import pack
from zlib import crc32, compress

def chunk(type, data):
  return pack('!I4s%dsi' % len(data), len(data), type, data, crc32(type + data))

width, height = 100, 20
depth, color_type = 8, 3

palette_data = pack("%dB" % (width * 3), *sum([[i * 255 / (width - 1), 0, 0] for i in range(width)], []))
img_data = pack("%dB" % (width + 1), *([0] + range(width))) * height

stdout.write('\x89PNG\r\n\x1a\n')
stdout.write(chunk('IHDR', pack("!IIBBBBB", width, height, depth, color_type, 0, 0, 0)))
stdout.write(chunk("PLTE", palette_data))
stdout.write(chunk("IDAT", compress(img_data, 9)))
stdout.write(chunk('IEND', ''))