I\'ve been searching all around for a simple solution to add sprites to my OpenGl GLUT simple moon lander game in c++ and it appears I must use bmp\'s since they\'re easiest
How to load a bmp on GLUT to use it as a texture?
Another very simple solution would be to use STB library, which can be found at GitHub - nothings/stb.
All what is needed is one source file, the header file "stb_image.h". It doesn't require to link any library file or to compile any additional source file.
Include the header file and enable image reading by the setting the preprocessor definition STB_IMAGE IMPLEMENTATION:
#define STB_IMAGE_IMPLEMENTATION
#include
The image file can be read by the function stbi_load:
const char *filename = .....; // path and filename
int req_channels = 3; // 3 color channels of BMP-file
int width = 0, height = 0, channels = 0;
stbi_uc *image = stbi_load( filename, &width, &height, &channels, 3 );
When the image is loaded to a texture object, then GL_UNPACK_ALIGNMENT has to be set to 1.
By default GL_UNPACK_ALIGNMENT is 4, so each line of an image is assumed to be aligned to 4 bytes. The pixels of a BMP-file in common have a size of 3 bytes and are tightly packed, this would cause a misalignment.
After loading the image, the memory can be freed by stbi_image_free:
GLuint texture_obj = 0;
if ( image != nullptr )
{
glGenTextures(1, &texture_obj);
glBindTexture(GL_TEXTURE_2D, texture_obj);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // default
stbi_image_free( image );
}