Embedding images in the code

The module image.c uses an image which is read from file. There are scenarios (for example, when we are sure we always want to use the very same image all times) in which it is better to include the image file in the source code of the program. This is very easy to do. First, the xpm file has to be included in the source code:

#include "monalisa.xpm"

Note that xpm files are valid C files, and this is why they can be included. It is also possible to cut and paste the file inside the source code. Looking at the source code of monalisa.xpm, we notice that it is in fact the declaration of a single variable monalisa (this is the same name of the file, but this is not necessary the case), which is an array of strings. What is important to our purposes is the name of this variable.

To use this image, we have to replace the command of reading the image from file with a command that builds an image staring from the data. This is obtained by simply replacing XpmReadFileToImage with XpmCreateImageFromData, which have the same arguments but the second one. This second argument (which was the file name) is now the name of the variabile that is declared in the image file. In our case, this is monalisa.

  /* create the image */
  if (XpmCreateImageFromData  (dpy, monalisa, &img, NULL, NULL)) {
      printf ("Error reading image\n");
      exit (1);

Note that the variabile name need not to coincide with the filename, and that it is the variable that has to be used for this call, not the filename.

The complete code of the module embed.c is, besides these small changes, identical to the module image.c.

Next: transparency