Skip to content

Instantly share code, notes, and snippets.

@NHollmann
Created August 27, 2019 20:33
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 NHollmann/9c774031f44a00a003ff710371fc9b17 to your computer and use it in GitHub Desktop.
Save NHollmann/9c774031f44a00a003ff710371fc9b17 to your computer and use it in GitHub Desktop.
Portable Anymap
// Portable Pixmap in C example.
// Compile with: gcc anymap.c -o anymap
// Tutorial: https://nicolashollmann.de/blog/writing-portable-anymap/
#include <stdio.h>
#define WIDTH 300
#define HEIGHT 200
// Uncomment to write binary instead of ASCII
//#define BINARY
int main()
{
FILE *outfile = fopen("out.ppm", "wb");
#ifdef BINARY
fprintf(outfile, "P6");
#else
fprintf(outfile, "P3");
#endif
fprintf(outfile, "\n%d %d\n255\n", WIDTH, HEIGHT);
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
int r = (x / (float)WIDTH) * 255;
int g = (x / (float)WIDTH) * 255;
int b = (y / (float)HEIGHT) * 255;
#ifdef BINARY
unsigned char colors[3] = {r, g, b};
fwrite(colors, 3, 1, outfile);
#else
fprintf(outfile, "%3d %3d %3d ", r, g, b);
#endif
}
#ifndef BINARY
fprintf(outfile, "\n");
#endif
}
fclose(outfile);
return 0;
}
// Portable Pixmap in C++ example.
// Compile with: g++ anymap.cpp -o anymap
// Tutorial: https://nicolashollmann.de/blog/writing-portable-anymap/
#include <iostream>
#include <fstream>
using namespace std;
#define WIDTH 300
#define HEIGHT 200
// Uncomment to write binary instead of ASCII
//#define BINARY
int main()
{
ofstream outfile;
outfile.open("out.ppm", ios::out | ios::binary);
#ifdef BINARY
outfile << "P6";
#else
outfile << "P3";
#endif
outfile << "\n" << WIDTH << " " << HEIGHT << "\n255\n";
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
int r = (x / (float)WIDTH) * 255;
int g = (x / (float)WIDTH) * 255;
int b = (y / (float)HEIGHT) * 255;
#ifdef BINARY
unsigned char colors[3] = {r, g, b};
outfile.write(colors, 3);
#else
outfile << r << " " << g << " " << b << " ";
#endif
}
#ifndef BINARY
outfile << "\n";
#endif
}
outfile.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment