Skip to content

Images and drawings in C ​

Basthon's C kernel is no longer limited to text: it builds images and draws, directly in the console and in the notebook.

Images pixel by pixel. The PPM format is a simple text file: a header, then a red-green-blue triplet per pixel. It is written with the functions of <stdio.h> alone, and image_show, declared in <image.h>, shows it:

c
#include <stdio.h>
#include <image.h>

FILE *f = fopen("gradient.ppm", "w");
fprintf(f, "P3\n256 256\n255\n");
for (int y = 0; y < 256; y++)
    for (int x = 0; x < 256; x++)
        fprintf(f, "%d %d %d\n", x, y, 128);
fclose(f);
image_show("gradient.ppm");

A way to work on two-dimensional arrays, structures and files through concrete examples: filters (negative, greyscale), binary format written with a single fwrite… The PGM, PBM and PNG formats are shown too.

Drawing. <canvas.h> gives access to a drawing area, with functions modelled on the browser's Canvas 2D: rectangles, circles, paths, text, CSS or RGB colours, pixels. The drawing is shown at the end of the run, or at each canvas_show() to show the steps of an algorithm:

c
#include <canvas.h>

canvas_create(300, 200);
canvas_fill_color("orange");
canvas_fill_rect(20, 20, 100, 60);
canvas_fill_rgb(0, 100, 200);
canvas_fill_circle(200, 100, 50);

Fractals and a PPM image drawn in C

The gallery offers five new examples: PPM images and filters, drawings and charts, fractals (Mandelbrot, recursive tree, Koch snowflake, Sierpiński triangle) in the notebook, and two programs for the console. Every function is described in the documentation of the C kernel.

See the fractals