/* bmp2hex - Converts a 1-bit/pixel image in a BMP image file into hexadecimal data for use in initializing a C or assembler program data array. Only works on 1-bit/pixel images, and probably not on all of those. Allan Weber, USC Dept. of Electrical Engineering, 11/7/06 */ #include #include // #define DEBUG unsigned char fileheader[14]; unsigned char infoheader[40]; main(int argc, char *argv[]) { int offset, width, height, bitcount; int n, widthbytes, padbytes; unsigned char *img, *p; int row, col, ch, invert; extern int optind; extern char *optarg; invert = 0; while ((ch = getopt(argc, argv, "i")) != -1) { switch (ch) { case 'i': invert = 1; break; case '?': usage(); exit(1); } } if (fread(fileheader, 1, 14, stdin) != 14) { fprintf(stderr, "Error reading fileheader\n"); exit(1); } if (strncmp(fileheader, "BM", 2) != 0) { fprintf(stderr, "File is not BMP format\n"); exit(1); } if (fread(infoheader, 1, 40, stdin) != 40) { fprintf(stderr, "Error reading fileheader\n"); exit(1); } /* Get some numbers from the headers */ offset = get4(fileheader + 10); width = get4(infoheader + 4); height = get4(infoheader + 8); bitcount = get2(infoheader + 14); #ifdef DEBUG printf("offset=%d, width=%d, height=%d, bitcount=%d\n", offset, width, height, bitcount); #endif /* Skip over any color table */ n = offset - (14 + 40); if (n > 0) fseek(stdin, n, SEEK_CUR); /* Check to make sure it's 1-bit per pixel */ if (bitcount != 1) { fprintf(stderr, "Unsupported bit depth - %d\n", bitcount); exit(1); } widthbytes = (width + 7) / 8; /* number of data bytes per line */ padbytes = ((width + 31) / 32) * 4; /* data+pad bytes per line */ #ifdef DEBUG printf("widthbytes=%d, padbytes=%d\n", widthbytes, padbytes); #endif /* Allocate memory for image data */ n = padbytes * height; if ((img = malloc(n)) == NULL) { fprintf(stderr, "Can\'t allocate memory\n"); exit(1); } /* Read in image data */ if (fread(img, 1, n, stdin) != n) { fprintf(stderr, "Error reading image data\n"); exit(1); } /* Loop through image data and print it out */ for (row = height-1; row >= 0; row--) { p = img + (padbytes * row); for (col = 0; col < widthbytes; col++) { ch = *p++; if (invert) ch ^= 0xff; printf("0x%02x, ", ch); } printf("\n"); } } /* Turn an Intel 4-byte quantity into an 32-bit value */ int get4(unsigned char *p) { int x; x = (*(p+3) << 24) + (*(p+2) << 16) + (*(p+1) << 8) + (*p); return(x); } /* Turn an Intel 2-byte quantity into an 32-bit value */ int get2(unsigned char *p) { int x; x = (*(p+1) << 8) + (*p); return(x); } usage() { fprintf(stderr, "bmp2hex [-i] < file.bmp\n"); }