Code:continents-black-on-white.c

From the change wiki

Generates a simple world map of the continents.

Input: File:countries.data-int16-8640x4320
Output: File:continents-black-on-white.png
Code dependency: Code:stb_image_write.h

Code

// Generates a black-and-white PNG world map of the continents, using NASA GPWv4 country indicator data
#define IN_FILE "data/countries.data-int16-8640x4320"
#define OUT_FILE "data/continents-black-on-white.png"
#define INPUT_WIDTH 8640
#define INPUT_HEIGHT 4320

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

int main() {
 unsigned char *bytes = malloc(INPUT_WIDTH*INPUT_HEIGHT);
 if (!bytes) {
  printf("Not enough memory\n");
  return -1;
 }
 short row[INPUT_WIDTH];
 FILE* in = fopen(IN_FILE, "r");
 if (in == NULL) {
  perror(IN_FILE);
  return 1;
 }
 printf("Reading %s...\n", IN_FILE);
 unsigned char *p = bytes;
 while (!feof(in)) {
  int nRead = fread(row, sizeof(short), INPUT_WIDTH, in);
  if (nRead == 0) break;
  for (int i=0; i<nRead; i++) {
   if (row[i] > 0 && row[i] < 1024)  *(p++) = 0;
   else                              *(p++) = 255;
  }
 }
 fclose(in);
 printf("Writing %s...\n", OUT_FILE);
 if (!stbi_write_png(OUT_FILE, INPUT_WIDTH, INPUT_HEIGHT, 1, bytes, INPUT_WIDTH)) {
  perror(OUT_FILE);
  return 2;
 }
 printf("Done.\n");
 free(bytes);
 return 0;
}