Last active
August 29, 2015 14:23
-
-
Save ph1ee/61b2d224bfc8f56d75f7 to your computer and use it in GitHub Desktop.
Convert 4-bit P5 format PGM file to C array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int convert(const char *var, FILE *in, FILE *out) { | |
char buf[256]; | |
char fmt[16] = { 0 }; | |
int width = 0, height = 0, depth = 0; | |
fgets(buf, sizeof(buf), in); // format | |
sscanf(buf, "%s", fmt); | |
fgets(buf, sizeof(buf), in); // image size | |
sscanf(buf, "%d %d", &width, &height); | |
fgets(buf, sizeof(buf), in); // bit depth | |
sscanf(buf, "%d", &depth); | |
// fprintf(stdout, "%s\n%d %d\n%d\n", fmt, width, height, depth); | |
if ((width & 1) != 0) { | |
fprintf(stderr, "error: even width is required: %d\n", width); | |
return -1; | |
} | |
if (depth != 15) { // 4-bit max value | |
fprintf(stderr, "error: only 4-bit depth is supported: %d\n", depth); | |
return -1; | |
} | |
fprintf(out, "unsigned char %s[] = {\n", var); | |
int i = 0, hi = 0; | |
for (i = 1; i <= width * height; i++) { | |
hi = fgetc(in); | |
if (hi == EOF) { | |
fprintf(stderr, "error: unexpected EOF\n"); | |
return -1; | |
} | |
fprintf(out, "0x%x, ", hi); | |
if (i % width == 0) { | |
fprintf(out, "\n"); | |
} | |
} | |
fprintf(out, "};\n"); | |
return 0; | |
} | |
int main(int argc, char *argv[]) { | |
int i; | |
for (i = 1; i < argc; i++) { | |
FILE *fin = fopen(argv[i], "r"); | |
// remove file extension | |
*strrchr(argv[i], '.') = '\0'; | |
// construct filename | |
char fname[256] = { 0 }; | |
snprintf(fname, sizeof(fname), "%s.c", argv[i]); | |
FILE *fout = fopen(fname, "w"); | |
if (fin != NULL && fout != NULL) { | |
if (convert(argv[i], fin, fout) < 0) { | |
fprintf(stderr, "error: failed to convert %s\n", argv[i]); | |
} | |
fclose(fin); | |
fclose(fout); | |
} | |
} | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment