aboutsummaryrefslogtreecommitdiff
path: root/src/ppm.c
blob: 7bc8bb7653c5766a651f15fd9d90df6ff19ea6ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "typedef.h"
#include "ppm.h"

void save_as_ppm(char* file_path, small_t *t, size_t width, size_t height, size_t scaler)
{
    FILE *fp = fopen(file_path, "wb");
    if(!fp) {
        fprintf(stderr, "ERROR: Could not open file: %s\n", file_path);
        exit(EXIT_FAILURE);
    }

    if(scaler == 0) {
        fprintf(stderr, "ERROR: Invalid value for scaler %ld\n", scaler);
        exit(EXIT_FAILURE);
    }

    fprintf(fp, "P6\n%ld %ld 255\n", width*scaler, height*scaler);

    for(size_t i = 0; i < height * scaler; i++)
        for(size_t j = 0; j < width * scaler; j++)
            for(int k = 0; k < 3; k++) {
                char c = t[((i/scaler) * width + (j/scaler))*3 + k];
                fwrite(&c, 1, 1, fp);
            }

    fclose(fp);
}

small_t *load_from_ppm(char *file_path, size_t *width, size_t *height)
{
    FILE *fp = fopen(file_path, "rb");
    if(!fp) {
        fprintf(stderr, "ERROR: Could not open file: %s\n", file_path);
        exit(EXIT_FAILURE);
    }

    char line[64] = {0};

    fgets(line, sizeof(line), fp);
    if(strncmp(line, "P6", 2) != 0) {
        fprintf(stderr, "ERROR: PPM header is not correct of file: %s\n", file_path);
        exit(EXIT_FAILURE);
    }

    fgets(line, sizeof(line), fp);
    *width  = atoi(strtok(line, " "));
    *height = atoi(strtok(NULL, " "));
    (void)strtok(NULL, " ");

    small_t *t = malloc((*width) * (*height ) * 3);

    fread(t, *width*3, *height, fp);

    fclose(fp);

    return t;
}

void free_ppm(small_t *t)
{
    free(t);
}