aboutsummaryrefslogtreecommitdiff
path: root/src/ppm.c
blob: 7ac29f36a4c92737f079396fd4c62f074c33723d (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
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ppm.h"

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

    fprintf(fp, "P6\n%d %d 255\n", width, height);

    for(int i = 0; i < height; i++)
        for(int j = 0; j < width; j++)
        {
            char c = (t[i * width + j] == 0) ? 255 : 0;
            for(int j = 0; j < 3; j++)
                fwrite(&c, 1, 1, fp);
        }

    // int scaler = 10;

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

    // for(int i = 0; i < height * scaler; i++)
    //     for(int 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);
}

int *load_from_ppm(char *file_path, int *width, int *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);

    int *t = malloc((*width) * (*height ) * sizeof(int));
    for(int i = 0; i < *height; i++)
        for(int 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(int *t)
{
    free(t);
}