Drawing Images in C

Home / 2025 / 12 / 26 / #c / #ppm

I watched Graphics API is irrelevant and learned a simple way to do graphics in C by using the simple PPM image format. I wanted to give it a try.

Here is code to generate an image:

#include <stdio.h>
#include <stdlib.h>

#define W 1024
#define H 768
#define MAX 255
#define THICKNESS 5

int is_cross(int x, int y, int thickness) {
    return abs(y*W/H - x) <= thickness || abs(y*W/H - W+x) <= thickness;
}

int main() {
    unsigned char r, g, b;
    int x, y;
    FILE* f;
    f = fopen("out.ppm", "wb");
    fprintf(f, "P6\n");
    fprintf(f, "%d %d\n", W, H);
    fprintf(f, "%d\n", MAX);
    for (y=0; y<H; y++) {
        for (x=0; x<W; x++) {
            if (is_cross(x, y, THICKNESS)) {
                r = 200;
                g = 200;
                b = 200;
            } else if (is_cross(x, y, THICKNESS*2)) {
                r = 100;
                g = 100;
                b = 100;
            } else {
                r = (MAX*x)/W;
                g = (MAX*y)/W;
                b = (MAX*x*y)/(W*H);
            }
            fputc(r, f);
            fputc(g, f);
            fputc(b, f);
        }
    }
    return 0;
}

And here is the result:

Image with gradient and a
cross generated from C code.

Pretty cool what you can do with just C code and no libraries.