Skip to content

Instantly share code, notes, and snippets.

@johnciacia
Created July 18, 2011 02:28
Show Gist options
  • Save johnciacia/1088428 to your computer and use it in GitHub Desktop.
Save johnciacia/1088428 to your computer and use it in GitHub Desktop.
Encode text in a BMP image format
//because I can...
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
int main(int argc, char **argv) {
if(argc != 3)
printf("%s <input-file> <output-file>\n", argv[0]);
FILE *input_file, *output_file;
long size;
char *buffer;
size_t result;
input_file = fopen(argv[1], "rb");
if(input_file == NULL) { fputs ("File error", stderr); exit(1); }
fseek(input_file, 0, SEEK_END);
size = ftell(input_file);
rewind(input_file);
buffer = (char*)malloc(sizeof(char)*size);
if (buffer == NULL) { fputs("Memory error", stderr); exit (2); }
result = fread(buffer, 1, size, input_file);
if (result != size) { fputs("Reading error", stderr); exit(3); }
uint8_t header[54] =
{
'B', 'M', //2 signature
0,0,0,0, //6 size of BMP file in bytes
0,0, //8 reserved must be zero
0,0, //10 reserved must be zero
54,0,0,0, //14 offset to start of image data
40,0,0,0, //18 size of BITMAPINFOHEADER structure, must be 40
0,0,0,0, //22 image width in pixels
0,0,0,0, //26 image height in pixels
1,0, //28 number of planes in the image, must be 1
24,0, //30 number of pits per pixel (1, 4, 8, or 24)
0,0,0,0 //34 compression type
//54 useless stuff
};
//Set the image size
header[2] = (uint8_t)(size + sizeof header);
header[3] = (uint8_t)((size + sizeof header) >> 8);
header[4] = (uint8_t)((size + sizeof header) >> 16);
header[5] = (uint8_t)((size + sizeof header) >> 24);
//Do something fance calculation for with the width/height
header[18] = (uint8_t)(size/3); //image width
header[22] = (uint8_t)(1); //image height
output_file = fopen(argv[2], "wb");
fwrite(header, sizeof header, 1, output_file);
fwrite(buffer, size + sizeof header, 1, output_file);
fclose(input_file);
fclose(output_file);
free (buffer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment