If you need a way to convert simply a small image into C++ / Obj C code that can be compiled by GCC or any other modern compiler there are a few utilities out there. In my case I was not happy with the results, so I wrote a few lines of code to do this.
What I needed is a simple code that fill an array of char that can then be used by OpenGL or custom pixel processing code. It’s so easy to load an image into an NSBitmapImageRep. Once you have this there are a few accessor like pixelsWide, bitmapData … that lets you play with the pixels and it’s then very easy to generate some text that will be C++ / Obj C compliant.
Here is a small 16 by 16 image converted into code with my utility:
int gImageWidth = 16;
int gImageHeight = 16;
int gImageBits = 24;
unsigned char gImagePixels[] = {
// line 0
0xf2,0xf1,0xf1,0xf1,0xf1,0xf1,0xf1,0xf1,0xf1,0xf1,0xf1,0xf1,
0xf1,0xf1,0xf1,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,
0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xef,0xf0,0xf0,0xef,0xef,0xef,
0xef,0xef,0xef,0xef,0xef,0xef,0xef,0xef,0xef,0xee,0xee,0xee,
// line 1
0xe5,0xe5,0xe5,0xe5,0xe5,0xe5,0xe4,0xe4,0xe4,0xe4,0xe4,0xe4,
0xe4,0xe4,0xe4,0xe4,0xe4,0xe4,0xe4,0xe3,0xe4,0xe3,0xe3,0xe3,
0xe3,0xe3,0xe3,0xe3,0xe3,0xe3,0xe3,0xe3,0xe3,0xe2,0xe2,0xe2,
0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe1,0xe1,0xe1,
// line 2
0xd7,0xd7,0xd7,0xd7,0xd7,0xd7,0xd7,0xd7,0xd7,0xd6,0xd6,0xd6,
0xd6,0xd6,0xd6,0xd6,0xd6,0xd6,0xd6,0xd6,0xd6,0xd5,0xd5,0xd5,
0xd5,0xd5,0xd5,0xd5,0xd5,0xd5,0xd4,0xd5,0xd5,0xd4,0xd4,0xd4,
0xd4,0xd4,0xd4,0xd4,0xd4,0xd4,0xd3,0xd3,0xd4,0xd3,0xd3,0xd3,
…
And here is the code of the small command line utility:
#import Cocoa/Cocoa.h
int main (int argc, const char * argv[])
{
if (argc >=3)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString * src_file = [[NSString alloc] initWithFormat: @”%s”, argv[1]];
NSData * raw = [NSData dataWithContentsOfFile: src_file];
if (raw)
{
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData: raw];
if (rep)
{
FILE * out = fopen (argv[2], “w”);
if (out)
{
int width = [rep pixelsWide];
int height = [rep pixelsHigh];
int bits = [rep bitsPerPixel];
int rowbytes = [rep bytesPerRow];
unsigned char * src = [rep bitmapData];
fprintf (out, “int gImageWidth = %ld;\n”, width);
fprintf (out, “int gImageHeight = %ld;\n”, height);
fprintf (out, “int gImageBits = %ld;\n”, bits);
fprintf (out, “unsigned char gImagePixels[] = {\n”);
for (int v=0; v