Skip to content

Commit

Permalink
Add much faster image writer (binary instead of text).
Browse files Browse the repository at this point in the history
  • Loading branch information
andportnoy committed Jan 12, 2019
1 parent 3574099 commit 752e5f4
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion evolve_image.c
Expand Up @@ -186,7 +186,7 @@ void write_images(Image **images, size_t n_images) {
sprintf(filename, "images/random%07lu.ppm", i);
file = fopen(filename, "w");
if (file) {
write_image(file, images[i]);
write_image_P6(file, images[i]);
fclose(file);
printf("\33[2K\rSaved image %lu...", i);
fflush(stdout);
Expand Down
2 changes: 1 addition & 1 deletion evolve_row.c
Expand Up @@ -207,7 +207,7 @@ void main_row_generation(int argc, char *argv[]) {
image = generate_image((size_t)width, (size_t)height, chosen_row_evolver);
file = fopen(argv[4], "w");
if (file) {
write_image(file, image);
write_image_P6(file, image);
fclose(file);
} else {
fprintf(stderr, "Failed to open file.\n");
Expand Down
11 changes: 10 additions & 1 deletion image.c
Expand Up @@ -58,7 +58,7 @@ void print_image(const Image *image) {
}
}

void write_image(FILE *file, const Image *image) {
void write_image_P3(FILE *file, const Image *image) {
size_t i, j;

/* Print PPM header. */
Expand All @@ -72,6 +72,15 @@ void write_image(FILE *file, const Image *image) {
}
}

void write_image_P6(FILE *file, const Image *image) {
/* Print PPM header. */
fprintf(file, "P6\n%lu %lu\n%d\n", image->width, image->height, COLOR_RANGE);
fwrite(image->pixels,
sizeof(*(image->pixels)),
(image->width)*(image->height),
file);
}

void set_random_image(Image *image) {
size_t length;
size_t i;
Expand Down
3 changes: 2 additions & 1 deletion image.h
Expand Up @@ -21,7 +21,8 @@ void write_pixel(FILE *file, const Pixel *pixel);
Pixel *pixel_at(const Image *image, size_t x, size_t y);
void set_random_row(Pixel *row, size_t width);
void print_image(const Image *image);
void write_image(FILE *file, const Image *image);
void write_image_P3(FILE *file, const Image *image);
void write_image_P6(FILE *file, const Image *image);
void set_random_image(Image *image);
Image *malloc_image(size_t width, size_t height);
Image *malloc_random_image(size_t width, size_t height);
Expand Down

0 comments on commit 752e5f4

Please sign in to comment.