【问题标题】:How can i fix this displayer image error in ImGui?如何在 ImGui 中修复此显示图像错误?
【发布时间】:2022-07-12 02:42:52
【问题描述】:

我已经开始用 ImGui 和 opengl 制作一个程序,除了图像的 stb。当我显示演示的默认图像时,它会正确显示。如果我使用 stb 加载一个并将其与 opengl 链接然后显示它,它看起来像这样。我不知道它可能是什么。顺便说一句,加载与窗口图标相同的图像就可以了。

加载图像的功能:

bool FeatherGUI::loadImage(std::string _path) {
    //Load texture from file
    CurrentImage.data = stbi_load(_path.c_str(), &CurrentImage.width, &CurrentImage.height, &CurrentImage.channels, 3);
    if (!CurrentImage.data) {
        fprintf(stderr, "Cannot load image '%s'\n", _path.c_str());
        CurrentImage.loaded = true;
        return false;
    }

    // Create a OpenGL texture identifier and binding
    glGenTextures(1, &CurrentImage.texture);
    glBindTexture(GL_TEXTURE_2D, CurrentImage.texture);

    // Setup filtering parameters for display
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    
    // Upload pixels into texture
    #if defined(GL_UNPACK_ROW_LENGTH) && !defined(__EMSCRIPTEN__)
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    #endif
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, CurrentImage.width, CurrentImage.height, 0, GL_RGB, GL_UNSIGNED_BYTE, CurrentImage.data);
    stbi_image_free(CurrentImage.data);
    
    CurrentImage.loaded = true;

    return true;
}

创建 GUI 的功能:

void FeatherGUI::BuildGUI() {
    using namespace ImGui;
    
    Begin("Imagen Displayer");
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / GetIO().Framerate, GetIO().Framerate);
    
    if (!CurrentImage.loaded) {
        //load image
        if (!loadImage("B:/naranja.png")) {
            Text("Error loading image");
        }
    }

    //Show CurrentImage data in ImGui
    if (CurrentImage.loaded) {
        Text("------------------------------------------------");
        Text("Identifier = %p", CurrentImage.texture);
        Text("Size = %d x %d", CurrentImage.width, CurrentImage.height);
        Text("Channels: %d", CurrentImage.channels);
    }

    //Show CurrentImage in ImGui
    if (CurrentImage.data != NULL) {
        Image((void*)(intptr_t)CurrentImage.texture, ImVec2(CurrentImage.width, CurrentImage.height));
    }
    
    End();
}

【问题讨论】:

    标签: c++ image opengl imgui


    【解决方案1】:

    默认情况下,OpenGL 假定图像的每一行的开头对齐到 4 个字节,因为GL_UNPACK_ALIGNMENT 参数默认为 4。由于图像有 3 个颜色通道 (GL_RGB),并且是紧密打包的图像的一行大小可能未对齐到 4 个字节。
    当将具有 3 个颜色通道的 RGB 图像加载到纹理对象并且 3*width 不能被 4 整除时,必须将 GL_UNPACK_ALIGNMENT 设置为 1,然后才能使用 glTexImage2D 指定纹理图像:

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, CurrentImage.width, CurrentImage.height, 0,
        GL_RGB, GL_UNSIGNED_BYTE, CurrentImage.data);
                 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2013-09-13
      • 2021-12-11
      • 2021-08-07
      • 1970-01-01
      相关资源
      最近更新 更多