I've been a game developer since 2005. After working 3 years in the game industry I've decided to go indie and make games. The first game was on June 2010 David is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Loading Images into OpenGL in iPhone

  • submit to reddit

So you can’t make a game without images, right? Well, actually you can but that’s another story.

But how can you load a jpg or a png and use then on OpenGLES?

First let’s make a simple class Texture2D

class Texture2D 
Texture2D(int texture id, int width, int height)
_textureId = id; _width = width; _height = height;

virtual ~Texture2D(void)
// Delete Texture from HGL Memory
glDeleteTextures(1, ((GLuint*)&_textureId));
int getTextureId() {return _textureId; }
int _textureId; // The reference ID of the texture in OpenGL memory
int _width;
int _height;

 Now for the code to actually load the image

Texture2D* IPhoneOperativeSystem::LoadImage(std::string imagefile)
// Id for texture
GLuint texture;
// Generate textures
glGenTextures(1, &texture);
// Bind it
glBindTexture(GL_TEXTURE_2D, texture);
// Set a few parameters to handle drawing the image at lower and higher sizes than original

NSString *path = [[NSString alloc] initWithUTF8String:imagefile.c_str()];

NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
UIImage *image = [[UIImage alloc] initWithData:texData];
if (image == nil)
return NULL;
// Get Image size
GLuint width = CGImageGetWidth(image.CGImage);
GLuint height = CGImageGetHeight(image.CGImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Allocate memory for image
void *imageData = malloc( height * width * 4 );
CGContextRef imgcontext = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );
CGColorSpaceRelease( colorSpace );
CGContextClearRect( imgcontext, CGRectMake( 0, 0, width, height ) );
CGContextTranslateCTM( imgcontext, 0, height - height );
CGContextDrawImage( imgcontext, CGRectMake( 0, 0, width, height ), image.CGImage );

// Generate texture in opengl
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
// Release context
// Free Stuff
[image release];
[texData release];

// Create and return texture
Texture2D* tex = new Texture2D(texture,width, height);
return tex;

 So right now you can do something like

Texture2D* tree_image = IPhoneOperativeSystem("tree_image.jpg");

For drawing, before sending your primitives just do something like:

For drawing, before sending your primitives just do something like:

This code should work on all iOS devices

Published at DZone with permission of David Amador, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)