我正在尝试使用lodepng(http://lodev.org/lodepng/)加载png图像并使用openGl进行绘制,但出现错误,并且我认为我正在尝试访问不可访问的 vector ID。但是我不知道为什么。

主要代码:

#include <iostream>
#include <glut.h>
#include <vector>
#include "lodepng.h"

using namespace std;

std::vector<unsigned char> img;
unsigned w, h;

void decodeOneStep(const char* filename)
{
    std::vector<unsigned char> image;
    unsigned width, height;

    //decode
    unsigned error = lodepng::decode(image, width, height, filename);
    cout << "w: " << width << " " << "h: " << height << endl;

    //if there's an error, display it
    if (error) std::cout << "decoder error " << error << ": " <<       lodepng_error_text(error) << std::endl;
    else
    {
        img = image;
        w = width;
        h = height;
        cout << "Success" << endl;
    }
}

void display(void)
{
    /*  clear all pixels  */
    glClear (GL_COLOR_BUFFER_BIT);

    glRasterPos2i(0,0);
    glDrawPixels(w,h, GL_RGBA, GL_UNSIGNED_INT, &img);


    glFlush ();
}

void init (void)
{
    /*  select clearing (background) color       */
    glClearColor (0.0, 0.0, 0.0, 0.0);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);

    decodeOneStep("eleTest.png");
    cout << img->size();
}
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize (800, 800);
    glutInitWindowPosition (300, 0);
    glutCreateWindow ("hello");
    init ();
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

错误是:
c&#43;&#43; - 使用lodePng和OpenGL显示png图像-LMLPHP

最佳答案

看来您的数据与glDrawPixels中的类型限定符不匹配

std::vector<unsigned char> img;
glDrawPixels(w,h, GL_RGBA, GL_UNSIGNED_INT, &img);

img每个通道包含1个字节的数据,但告诉OpenGL每个通道应读取4个字节(一个整数)。尝试将GL_UNSIGNED_INT切换到GL_UNSIGNED_BYTE。

由于我不知道导入程序库:您将必须确保图像确实具有Alpha通道。否则,您可能会遇到类似问题。

注意&img不一定是 vector 中第一个元素的地址。您至少应该使用&img[0],如LodePNG的opengl示例中所示。

10-08 12:20