Rickard Lindberg | Blog | Projects
All Posts | 2025 | 2025-12 | 2025-12-26 | All Bibs | All Tags | #c | #ppm

Drawing Images in C

Written by Rickard Lindberg .

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.

What is Rickard working on and thinking about right now?

Every month I write a newsletter about just that. You will get updates about my current projects and thoughts about programming, and also get a chance to hit reply and interact with me. Subscribe to it below.

Powered by Buttondown (My Newsletter)

I'm Rickard Lindberg from Sweden. This is my home on the web. I like programming. I like both the craft of it and also to write software that solves problems. I also like running.

Me elsewhere: GitHub, Mastodon.