Archive for September, 2009

Easily converting an image into C++ / Obj C code..

Posted in Programming on September 30th, 2009 by admin – Be the first to comment

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

// line 1

// line 2

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 {
unsigned char * pixels = src;
fprintf (out, “// line %ld\n”, v);
for (int h=0; h {
fprintf (out, “0x%x,0x%x,0x%x,”, pixels[0], pixels[1], pixels[2]);
pixels +=3;
if (((h+1) % 4) == 0)
fprintf (out, “\n”);
fprintf (out, “\n”);

src += rowbytes;
fprintf (out, “};”);
fclose (out);
[pool release];
printf (“syntax is image2code src dst”);

return 0;

Just compile it as a command line utility with XCode and link against the cocoa framework and you are ready to convert simply image into C++ / Obj C code