Skip to content

Instantly share code, notes, and snippets.

@tomty89
Last active June 7, 2023 10:11
Show Gist options
  • Save tomty89/c007edfc66b6043c7fea966fcfa1b97d to your computer and use it in GitHub Desktop.
Save tomty89/c007edfc66b6043c7fea966fcfa1b97d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define B 4
static unsigned char* ntb(unsigned char b[], unsigned int n) {
b[0] = n >> 24;
b[1] = n >> 16;
b[2] = n >> 8;
b[3] = n;
return b;
}
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr, "Usage: %s width height image_file\n", argv[0]);
exit(1);
}
unsigned char b[4];
int pic_type = 3; // Cover (front);
fwrite(ntb(b, pic_type), B, 1, stdout);
char mime_type[] = "image/jpg";
int mt_len = strlen(mime_type);
fwrite(ntb(b, mt_len), B, 1, stdout);
fwrite(mime_type, mt_len, 1, stdout);
fwrite(ntb(b, 0), B, 1, stdout); // description length (= 0)
fwrite(ntb(b, atoi(argv[1])), B, 1, stdout); // width
fwrite(ntb(b, atoi(argv[2])), B, 1, stdout); // height
fwrite(ntb(b, 24), B, 1, stdout); // color depth in bits-per-pixel
fwrite(ntb(b, 0), B, 1, stdout); // non-indexed picture
FILE* image = fopen(argv[3], "rb");
if (!image) {
fprintf(stderr, "cannot open image file\n");
exit(1);
}
fseek(image, 0, SEEK_END);
int file_size = ftell(image);
fwrite(ntb(b, file_size), B, 1, stdout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment