How to embed a texture for use with OpenGL into a C array?

Viewed 157

I don't want the error texture of my game engine to rely on an external file, because that file might be deleted, which defeats the purpose of having an error texture. How can I convert an image file into a C-sytle char array that I can read using glTexImage2D?

2 Answers

First, convert your source image file to the 'raw' format (while "remembering" the dimensions of your image in a pair of variables). For this you can use the ImageMagick's convert tool.

The sample for greyscale images conversion is given by this answer. For RGB images either write your own image-to-binary-file converter (since you probably know how to load RGB images for other textures, or use the STB or similar library to load it and then save the image data to a binary file), or (if no automation of this conversion step is needed) just use some GUI tool to save the RAW image.

Then use a tool named bin2h (binary file to C header) which takes a file as an input (your 'raw' file) and outputs a C header with a byte array.

One of such tools can be found at Bin2H@github

Then use the declared array (and a pair of variables with texture dimensions) as an argument to glTexImage2D.

If you have no aversions against 'gimp', gimp has a .h or .c exporter. In that way you have direct access to the dimensions and buffer of your image. Although it is not compressed, so be aware if you want to use a large Image.

Related