You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenGL纹理映射到矩形时出现断裂错位问题及解决方案

OpenGL非4倍数尺寸图片纹理映射异常修复方案

问题现象

在OpenGL中将PNG格式图片映射到矩形时,出现纹理断裂为两块的异常:左下角、右下角区域显示正常,但顶部左右区域的纹理映射颠倒。

相关业务代码

program pro("vertex.vs", "fragment.fs");

unsigned int VAO;
glGenVertexArrays(1, &VAO);

// triangle
float vertices[] = {
    // positions          // colors           // texture coords
    0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
    0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom right
    -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom left
    -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f // top left
};
unsigned int indices[] = {
    0, 1, 3,// first triangle
    1, 2, 3 // second triangle
};

unsigned int VBO, EBO;
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);

glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);

unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true);

unsigned char* data = stbi_load("图片22.jpg", &width, &height, &nrChannels, 0);
if (data) {
    std::cout<<width<<" "<<height<<" "<<nrChannels<<std::endl;
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
} else {
    std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);

pro.use();
pro.setInt("ourTexture", 0);

复现规律

替换使用512*512尺寸的图片测试时,纹理可正常显示,仅宽高非4整数倍的图片会触发该异常。

根因说明

触发异常的图片宽高不是4的整数倍,不符合OpenGL默认像素解包对齐规则。

修复方案

在调用glTexImage2D加载纹理前,添加如下代码修改像素解包对齐规则即可:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

内容的提问来源于stack exchange,提问作者Takaaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:06:10