aboutsummaryrefslogtreecommitdiff
path: root/src/ppm.c
diff options
context:
space:
mode:
authorkartofen <mladenovnasko0@gmail.com>2022-08-08 16:16:47 +0300
committerkartofen <mladenovnasko0@gmail.com>2022-08-08 16:16:47 +0300
commitf158268a0d59133b7cef538b3fa57ece16f2981d (patch)
tree846760a497a6c08d61adae96cbce6ffe4e6383c6 /src/ppm.c
Big Bang
Diffstat (limited to 'src/ppm.c')
-rw-r--r--src/ppm.c81
1 files changed, 81 insertions, 0 deletions
diff --git a/src/ppm.c b/src/ppm.c
new file mode 100644
index 0000000..7ac29f3
--- /dev/null
+++ b/src/ppm.c
@@ -0,0 +1,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);
+}