I am trying to crop an image loaded thanks to SOIL library, before using it as a texture.
This is what I would like to do:
unsigned char * img = SOIL_load_image("img.png", &w, &h, &ch, SOIL_LOAD_RGBA);
// crop img ...
// cast it into GLuint texture ...
You can load a portion of your image by utilizing the glPixelStorei
functionality:
// the location and size of the region to crop, in pixels:
int cropx = ..., cropy = ..., cropw = ..., croph = ...;
// tell OpenGL where to start reading the data:
glPixelStorei(GL_UNPACK_SKIP_PIXELS, cropx);
glPixelStorei(GL_UNPACK_SKIP_ROWS, cropy);
// tell OpenGL how many pixels are in a row of the full image:
glPixelStorei(GL_UNPACK_ROW_LENGTH, w);
// load the data to a previously created texture
glTextureSubImage2D(texure, 0, 0, 0, cropw, croph, GL_SRGB8_ALPHA8, GL_UNSIGNED_BYTE, img);
Here's a diagram from the OpenGL spec that might help:
EDIT: If you're using older OpenGL (older than 4.5) then replace the glTextureSubImage2D
call with:
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, cropw, croph, 0, GL_RGBA, GL_UNSIGNED_BYTE, img);
Make sure to create and bind the texture prior to this call (same way you create textures normally).