Embedding Image Data with wxWidgets

I'm a big fan of wxWidgets, principally because it gives me a uniform coding platform to write GUI apps on any operating system. On Windows we have always had the option to embed binary data like images in our programs using resource files, but a similar functionality was unavailable to the UNIX programmer. Until now.

The trick itself isn't exactly new. C and C++ have always had the ability to create a static initialized variable, and probably smarter people than I have figured out how to stuff all kinds of things directly into their executable by taking advantage of this. Encryption libraries for instance use this feature to embed large chunks of data used in data transforms.

What I have done is create a program which takes your binary data, encodes it as a very large static character array, and writes that into an include file. Then whenever you need to access that data all you need to do is access that particular variable. I just used it to embed the PNG images that I use for backgrounds and logos into the burnbox (http://burnbox.lazarusid.com).

The trick for using it goes like this:

#include <wx/mstream.h>
#include <wx/image.h>
#include "myimage.h"

   ...

  wxMemoryInputStream mem(myimage_png, myimage_png_size);
  wxImage img(mem);

That's it. encodefile turns type binary file myimage.png into an include file, myimage.h, which defined variable myimpage_png as an unsigned character array, and the macro myimage_png_size as the size of the data.

There are plenty of other opportunities for this as well. For instance if you write a library that may need to deploy and run another program, you can embed the stripped program directly into your library. Then when it is needed, it's a simple matter of writing that program to disk and executing it. That's useful, for instance, if you are writing a library which will update your software via the web, because a program really can't overwrite itself, but another program can easily once the first program has exited.

If you wind up using encodefile in your own work, drop me a line and tell me what you've done with it. You may give somebody else (maybe even me) a brilliant idea for using it.

Update: The original encodefile.c attached to this article had a fatal flaw under Windows. I have since corrected it so that files are opened in binary mode. If you run into compile problems on UNIX systems, remove O_BINARY from the open call and you should be back in business.

AttachmentSize
encodefile.c6 bytes
ยป

Comments

Locksmith services

Terrific work! The feedback delivered was extremely helpful. I really hope that you carry on the good work done.
hollywood locksmith fl
locksmith jupiter
Terrific work! The feedback delivered was extremely helpful. I really hope that you carry on the good work done.
hollywood locksmith fl
locksmith jupiter