您可以利用glPixelStorei 功能加载图像的一部分:
// 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);
以下是来自 OpenGL 规范的图表,可能会有所帮助:
编辑:如果您使用的是较旧的 OpenGL(早于 4.5),请将 glTextureSubImage2D 调用替换为:
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, cropw, croph, 0, GL_RGBA, GL_UNSIGNED_BYTE, img);
确保在此调用之前创建并绑定纹理(与通常创建纹理的方式相同)。