Skip to content

Instantly share code, notes, and snippets.

@bedekelly
Created October 28, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bedekelly/ff72d25e36ebdb2d571413884def46b3 to your computer and use it in GitHub Desktop.
Save bedekelly/ff72d25e36ebdb2d571413884def46b3 to your computer and use it in GitHub Desktop.
Write an image from a C program
#include <stdio.h>
#include <stdlib.h>
void get_color(int i, int j, char color[]) {
static char r = 0, g = 0, b = 0;
r++; g--; b++;
color[0] = r;
color[1] = g;
color[2] = b;
}
/* Write the header for a PPM file. */
void write_header(FILE *fp, int dimx, int dimy) {
fprintf(fp, "P6\n"); // Write magic chars.
fprintf(fp, "%d %d\n", dimx, dimy); // Write width and height.
fprintf(fp, "255\n"); // Write max colour value.
}
/* Generate a Mandelbrot image. */
void generate_file(int dimx, int dimy) {
// Create a file and write to it.
FILE *fp = fopen("mandelbrot.ppm", "wb");
write_header(fp, dimx, dimy);
// For each coordinate, calculate its color then write to file.
char color[3];
for (int j=0; j<dimy; ++j)
for (int i=0; i<dimx; ++i)
{
get_color(i, j, color);
fwrite(color, 1, 3, fp);
}
// Close the file pointer to clean up.
fclose(fp);
}
int main(int argc, char *argv[]) {
// Grab our parameters from the system args.
int dimx = atoi(argv[1]);
int dimy = atoi(argv[2]);
// Write the file with the given resolution.
generate_file(dimx, dimy);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment