How to remove black background from textures in OpenGL

Auraomega picture Auraomega · Jun 16, 2009 · Viewed 7.1k times · Source

I'm looking for a way to remove the background of a 24bit bitmap, while keeping the main image totally opaque, up until now blending has served the purpose but now I need to keep the main bit opaque. I've searched on Google but found nothing helpful, I think I'm probably searching for the wrong terms though, so any help would be greatly appreciated.

Edit: Yes sorry, I'm using black right now as the background.

Answer

Andrew Garrison picture Andrew Garrison · Jun 16, 2009

When you are creating the texture for OpenGL, you'll want to create the texture as a 32-bit RGBA texture. Create a buffer to hold the contents of this new 32-bit texture and iterate through your 24-bit bitmap. Every time you come across your background color, set the alpha to zero in your new 32-bit bitmap.

struct Color32;
struct Color24;

void Load24BitTexture(Color24* ipTex24, int width, int height)
{
   Color32* lpTex32 = new Color32[width*height];

   for(x = 0; x < width; x++)
   {
      for(y = 0; y < height; y++)
      {
         int index = y*width+x;
         lpTex32[index].r = ipTex24[index].r;
         lpTex32[index].g = ipTex24[index].g;
         lpTex32[index].b = ipTex24[index].b;

         if( ipTex24[index] == BackgroundColor)
            lpTex32[index].a = 0;
         else
            lpTex32[index].a = 255;
      }
   }

   glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, lpTex32);

   delete [] lpTex32;
}