(帮助)加载BMP文件时出错

时间:2015-05-18 00:09:52

标签: c++ opengl textures

在RAM内存中加载BMP文件时遇到一些问题。

显然,图像加载得很好但是当OpenGL程序显示它时看起来很糟糕。该程序不会抛出任何错误(它在C ++中)

代码:

TEXTURE::TEXTURE(const char *path) {
    unsigned char header[54];
    unsigned int dataPos;
    unsigned int width, height, size;
    unsigned char *data;
    FILE *filePointer = fopen(path, "rb");

    if(filePointer == NULL)
        printf_s("Error openning image file at '%s'!", path);

    if(!fread(header, 1, 54, filePointer))
        printf_s("Error, file at '%s' isn't a real BMP file.", path);

    if(header[0] != 'B' || header[1] != 'M')
        printf_s("Error, file at '%s' isn't a real BMP file.", path);

    dataPos = *(int *)&header[0x0A];
    size    = *(int *)&header[0x22];
    width   = *(int *)&header[0x12];
    height  = *(int *)&header[0x16];

    if(!size)
        size = width * height * 3;

    if(!dataPos)
        dataPos = 54;

    data = new unsigned char[size];
    fread(data, 1, size, filePointer);

    fclose(filePointer);

    glGenTextures(1, &texID);

    glBindTexture(GL_TEXTURE_2D, texID);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

    glBindTexture(GL_TEXTURE_2D, 0);
}

结果(图片上的信息并不重要):

(我无法发布图片......)http://i.stack.imgur.com/Ny2YD.jpg

原始图片:http://k33.kn3.net/C/B/A/4/0/C/DB2.bmp

顶点着色器源:

#version 330 core

layout(location = 0) in vec4 position;
layout(location = 1) in vec2 texCoords;

out DATA {
    vec2 texCoords;
} vs_out;

void main() {
    gl_Position = position;

    vs_out.texCoords = texCoords;
}

片段着色器源:

#version 330 core

layout(location = 0) out vec4 color;

in DATA {
    vec2 texCoords;
} fs_in;

uniform sampler2D sampler;

void main() {
    color = texture(sampler, fs_in.texCoords);
}

1 个答案:

答案 0 :(得分:0)

尝试使用SOIL库 很容易将任何类型的图像自动加载为纹理,请参阅里面的test_SOIL.cpp示例,这将有所帮助