Convert text to an image

Jul 02, 2011

Inspired by this post, I decided to write a file to bmp converter (because I have nothing better to do with my life).

//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 fancy 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;
}

dhcp197-066:~ johnciacia$ cat hello.c
#include <stdio.h>
int main(void) {
	printf("Hello, World!\n");
	return 0;
}
dhcp197-066:~ johnciacia$ cat hello.bmp
BM?6(#include <stdio.h>
int main(void) {
	printf("Hello, World!\n");
	return 0;
}
dhcp197-066:~ johnciacia$ hexdump hello.bmp
0000000 42 4d 84 00 00 00 00 00 00 00 36 00 00 00 28 00
0000010 00 00 1a 00 00 00 01 00 00 00 01 00 18 00 00 00
0000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000030 00 00 00 00 00 00 23 69 6e 63 6c 75 64 65 20 3c
0000040 73 74 64 69 6f 2e 68 3e 0a 0a 69 6e 74 20 6d 61
0000050 69 6e 28 76 6f 69 64 29 20 7b 0a 09 70 72 69 6e
0000060 74 66 28 22 48 65 6c 6c 6f 2c 20 57 6f 72 6c 64
0000070 21 5c 6e 22 29 3b 0a 09 72 65 74 75 72 6e 20 30
0000080 3b 0a 7d 0a 00 00 00 00 00 00 00 00 00 00 00 00

(there is a small problem somewhere that leads to extra padding at the end, but oh well, they are null bytes)