#include #include #include #include "ppm.h" void save_as_ppm(char* file_path, int *t, size_t width, size_t 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%ld %ld 255\n", width, height); // for(size_t i = 0; i < height; i++) // for(size_t 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 = 5; 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, 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); int *t = malloc((*width) * (*height ) * sizeof(int)); 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(int *t) { free(t); }