Advertisement
chrisasl

bmp loader

Feb 6th, 2013
460
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. GLuint loadBMP_custom(const char* imagepath)
  2. {
  3.     // Data read from the header of the BMP file
  4.     unsigned char header[54]; // Each BMP file begins by a 54-bytes header
  5.     unsigned int dataPos;     // Position in the file where the actual data begins
  6.     unsigned int width, height;
  7.     unsigned int imageSize;   // = width*height*3
  8.     // Actual RGB data
  9.     unsigned char * data;
  10.  
  11.     // Open the file
  12.     FILE * file = fopen(imagepath,"rb");
  13.     if (!file){printf("Image could not be opened\n"); return 0;}
  14.  
  15.  
  16.     if ( fread(header, 1, 54, file)!=54 )
  17.     {   // If not 54 bytes read : problem
  18.         printf("Not a correct BMP file\n");
  19.         return false;
  20.     }
  21.  
  22.     if ( header[0]!='B' || header[1]!='M' )
  23.     {
  24.         printf("Not a correct BMP file\n");
  25.         return 0;
  26.     }
  27.     // Read ints from the byte array
  28.     dataPos    = *(int*)&(header[0x0A]);
  29.     imageSize  = *(int*)&(header[0x22]);
  30.     width      = *(int*)&(header[0x12]);
  31.     height     = *(int*)&(header[0x16]);
  32.  
  33.     // Some BMP files are misformatted, guess missing information
  34.     if (imageSize==0)    imageSize=width*height*3; // 3 : one byte for each Red, Green and Blue component
  35.     if (dataPos==0)      dataPos=54; // The BMP header is done that way
  36.  
  37.     // Create a buffer
  38.     data = new unsigned char [imageSize];
  39.  
  40.     // Read the actual data from the file into the buffer
  41.     fread(data,1,imageSize,file);
  42.  
  43.     //Everything is in memory now, the file can be closed
  44.     fclose(file);
  45.  
  46.  
  47.     // Create one OpenGL texture
  48.     GLuint textureID;
  49.     glGenTextures(1, &textureID);
  50.  
  51.     // "Bind" the newly created texture : all future texture functions will modify this texture
  52.     glBindTexture(GL_TEXTURE_2D, textureID);
  53.  
  54.     // Give the image to OpenGL
  55.     glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, data);
  56.  
  57.     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  58.     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  59.  
  60.     return textureID;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement