Martin Karlsson /

I hope at least googlebot reads this blog

Forgotten trick

There exists an image format that is so simple that converting a 2d array list of pixel values is only 6 lines of Python

def pbm(pix2d,valrange):
    print("%d %d" % (len(pix2d[0]),len(pix2d)))
    print("%d" % (valrange))
    for pixrow in pix2d:
        print(" ".join([str(pix) for pix in pixrow]))

The NetPBM format! This implementation actually only covers the "P2" variant of the format (gray-scale): P1 is monochrome and P3 is full RGB. There are also binary variants of these P4-P6.

The format is not the forgotten trick though. See the code? No file handling! The trick is to let the shell handle this. Lets generate a small image (one-liners are fun!).

pixels = [[(y*x) % 64 for x in range(64)] for y in range(64)]

Running this will dump the image data straight to terminal, which can be nice for debugging.


Writing the image to disk is easy though:

$python > test.pbm

Saying that this is a "forgotten trick" is of course pure click bait, meant to anger you. I should have said that this was forgotten by me. I often find myself writing code that both write data to a textile and dumps the lines to the terminal for debugging. Well, that stops now.

Get in touch: martin [at]