如何裁剪加载 SOIL 的图像

How to crop an SOIL loaded image

我正在尝试裁剪通过 SOIL 库加载的图像,然后再将其用作纹理。

这就是我想做的事情:

unsigned char * img = SOIL_load_image("img.png", &w, &h, &ch, SOIL_LOAD_RGBA);
// crop img ...
// cast it into GLuint texture ...

您可以使用 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);

确保在此调用之前创建并绑定纹理(与通常创建纹理的方式相同)。