How to load a texture in Android OpenGL ES

Here is how you can easily load a texture from any image format - PNG, BMP, JPG etc.. in OpenGL ES in Android.

**Before you begin the code, you need to import your images into your project's /res/drawable/ folder. Just right click the project in eclipse and select import to do that.**

//First setup the integer array to hold texture numbers which OpenGL generates
int texture[] = new int[1];

//Generate and bind to the texture (gl is my GL10 object)
gl.glGenTextures(1, texture, 0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]);

//Setup the texture co-ordinates
float texCoords[] = {
0.0f, 0.0f,
1.0f, 0.0f,.......};
FloatBuffer texcoords = FloatBuffer.wrap(texCoords);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texcoords);
Bitmap wood = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.myimagefilenamewithoutextension);

//Setup optional texture parameters
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

//Set the texture image
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, wood, 0);

//Enable texture related flags (Important)
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

Hope that helped you.. please let me know any problems

Comments

  1. yay, thank you for this piece of code !

    ReplyDelete
  2. Why force people to disable add trackers to make a half penny when they can disable css or view source,... to get to the content? I don't want to be tracked.

    ReplyDelete

Post a Comment

Popular posts from this blog

DoTween - The Big Demo

Download Android SDK standalone for offline installation

Setting up Visual Studio Code for Haxe Development - Hello World on Mac