aboutsummaryrefslogtreecommitdiff
path: root/src/ppm.c
blob: 22bfaa5c7cf12a1c32fdc3f68498c69e19dbda1e (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
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <stdlib.h>
#include <string.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++)
        {
            char c = (t[(i/scaler) * width + (j/scaler)] == 0) ? 255 : 0;
            for(int j = 0; j < 3; j++)
                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, " ");

    char *pixels = malloc((*width) * (*height ) * 3);

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

    small_t *t = malloc((*width) * (*height));
    for(size_t i = 0; i < *height; i++)
        for(size_t j = 0; j < *width; j++)
            t[i * *width + j] = (pixels[(i * *width + j) * 3] == 0) ? 1 : 0;

    free(pixels);

    fclose(fp);

    return t;
}

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