add basic image manipulation functions

This commit is contained in:
Bruno BELANYI 2020-11-10 16:31:32 +01:00
parent cceed9fc84
commit 5c071adb8c
6 changed files with 76 additions and 0 deletions

View file

@ -9,7 +9,9 @@ project(
)
sources = [
'src/image.c',
'src/main.c',
'src/ppm.c',
]
executable(

20
src/image.c Normal file
View file

@ -0,0 +1,20 @@
#include "image.h"
#include <stdlib.h>
struct image *create_image(size_t w, size_t h) {
// FIXME: not checking for overflow
struct image *i = malloc(w * h * sizeof(*i->buf) + sizeof(*i));
if (!i)
return NULL;
i->w = w;
i->h = h;
return i;
}
void destroy_image(struct image *image) {
free(image);
}

19
src/image.h Normal file
View file

@ -0,0 +1,19 @@
#ifndef IMAGE_H
#define IMAGE_H
#include <stddef.h>
struct image {
size_t w;
size_t h;
struct pixel {
unsigned char r;
unsigned char g;
unsigned char b;
} buf[];
};
struct image *create_image(size_t w, size_t h);
void destroy_image(struct image *image);
#endif /* !IMAGE_H */

View file

@ -1,3 +1,6 @@
#include "image.h"
#include "ppm.h"
int main(void) {
return 0;
}

22
src/ppm.c Normal file
View file

@ -0,0 +1,22 @@
#include "ppm.h"
#include <stdio.h>
#include "image.h"
void print_ppm(const struct image *image, FILE *f) {
// Header
fputs("P3\n", f);
fprintf(f, "%zu %zu\n", image->w, image->h);
fputs("255\n", f);
// One row per line
for (size_t i = 0; i < image->h; ++i) {
for (size_t j = 0; j < image->w; ++j) {
if (j != 0)
fputc(' ', f);
const struct pixel *p = &image->buf[i * image->w + j];
fprintf(f, "%hhu %hhu %hhu", p->r, p->g, p->b);
}
fputc('\n', f);
}
}

10
src/ppm.h Normal file
View file

@ -0,0 +1,10 @@
#ifndef PPM_H
#define PPM_H
#include <stdio.h>
struct image; // Forward declaration
void print_ppm(const struct image *image, FILE *f);
#endif /* !PPM_H */