add basic image manipulation functions
This commit is contained in:
parent
cceed9fc84
commit
5c071adb8c
|
@ -9,7 +9,9 @@ project(
|
|||
)
|
||||
|
||||
sources = [
|
||||
'src/image.c',
|
||||
'src/main.c',
|
||||
'src/ppm.c',
|
||||
]
|
||||
|
||||
executable(
|
||||
|
|
20
src/image.c
Normal file
20
src/image.c
Normal 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
19
src/image.h
Normal 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 */
|
|
@ -1,3 +1,6 @@
|
|||
#include "image.h"
|
||||
#include "ppm.h"
|
||||
|
||||
int main(void) {
|
||||
return 0;
|
||||
}
|
||||
|
|
22
src/ppm.c
Normal file
22
src/ppm.c
Normal 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);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue