Hacker News new | ask | show | jobs
by st_goliath 1252 days ago
The Netbpm format is amazing if you quickly want to try something out and need to generate an image of some sorts. The P6 binary format is even simpler, you write the header followed by a raw pixel data blob, e.g.:

    fprintf(stdout, "P6\n%d %d\n255\n", WIDTH, HEIGHT);
    fwrite(image, 1, WIDTH * HEIGHT * 3, stdout);
Yes, I know, this obviously misses error handling, etc... The snippet is from a simple Mandelbrot renderer I cobbled together for a school exam exercise many moons ago: https://gist.github.com/AgentD/86445daed5fb21def3699b8122ea2...

The simplicity of the format nicely limits the image output to the last 2 lines here.

1 comments

I use this all the time. I love that it's simple enough that I can type something like those two lines off the top of my head at this point. And as an alternative to that fwrite(), another common pattern that I use is:

    for (int y = 0; y < HEIGHT; ++y)
        for (int x = 0; x < WIDTH; ++x)
        {
            // ... compute r, g, and b one pixel at a time
            printf("%c%c%c", r, g, b);
        }
I also find ImageMagick very convenient for working with the format when my program writes a PPM to stdout:

    ./myprog | convert - foo.png
or:

    ./myprog | display -