Loading images into OpenGL in iPhone

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 
{
public:
	Texture2D(int 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; }
protected:
	int _textureId;   // The reference ID of the texture in OpenGL memory
        int _width;
        int _height;
};

Now for the code to actually load the image

static 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
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); 
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
 
 
	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
	CGContextRelease(imgcontext);
	// Free Stuff
        free(imageData);
       [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::LoadImage("tree_image.jpg");

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

glBindTexture(GL_TEXTURE_2D, tree_image->getTextureId());

This code should work on all iOS devices

Back to Top