#include #include #include #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); }