Search code examples
cc-preprocessorimage-file

#include an image in ansi C


I am writing a program that creates an image file. I want the "original" image to be hard-coded in the program's binary.

I was thinking...

char image[] = {
#include"image.jpg"
}

But I need to somehow convert the image into a format that can be #included into a c file as a char array?


Solution

  • Ok, use the unix tool xxd to create a c char array import of a given binary file, Like so:

    $ xxd -i imgfile.dat > imgfile.h
    

    This should produce output like:

    unsigned char imgfile[] = {
      0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a
    };
    unsigned int imgfile_len = 12;
    

    See also: "#include" a text file in a C program as a char[]