Skip to content

Instantly share code, notes, and snippets.

@andrewgiessel
Created July 29, 2015 18:42
Show Gist options
  • Save andrewgiessel/d5e1a11604af4aee5962 to your computer and use it in GitHub Desktop.
Save andrewgiessel/d5e1a11604af4aee5962 to your computer and use it in GitHub Desktop.
import numpy as np
import base64, zlib, struct
from IPython.display import HTML
def write_png(buf, width, height):
""" buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBARGBA... """
# reverse the vertical line order and add null bytes at the start
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'')])
buf = (np.random.random((100,100,4))*255).astype(np.uint8)
buf[:50,:50,0] = 10
buf[:50,:50,1] = 10
buf = buf.tobytes()
data = write_png(buf, 100, 100)
with open("my_image.png", 'wb') as fd:
fd.write(data)
s = "data:image/png;base64,"+base64.b64encode(data)
HTML('<img src="{}">'.format(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment