将位图图像加载到 openGL 程序中

Loading a Bitmap Image into openGL program

我正在尝试将位图加载到我的 openGL 3d object,但是我收到此错误:

loadbitmap - bitcount failed = 8;

我想要做的是我有一个 object 和 3 个独立的位图图像(Body,眼睛,头部)位图图像,所以我将尝试绘制纹理直到矢量 6498,它们是 body 部分的三角形。

此错误消息不是来自编译器,它是从此文件手动打印的:

#ifndef _Bitmap_
#define _Bitmap_

#include "glad/glad.h"
#include <stdio.h>
#include <windows.h>
#include <wingdi.h>

GLuint loadbitmap(const char* filename, unsigned char*& pixelBuffer, BITMAPINFOHEADER* infoHeader, BITMAPFILEHEADER* fileHeader)
{
    FILE* bitmapFile;

    errno_t err = fopen_s(&bitmapFile, filename, "rb");
    if (err != 0 || bitmapFile == NULL)
    {
        printf("loadbitmap - open failed for %s\n", filename);
        return NULL;
    }

    fread(fileHeader, sizeof(BITMAPFILEHEADER), 1, bitmapFile);

    if (fileHeader->bfType != 0x4D42)
    {
        printf("loadbitmap - type failed \n");
        return NULL;
    }

    fread(infoHeader, sizeof(BITMAPINFOHEADER), 1, bitmapFile);

    if (infoHeader->biBitCount < 24)
    {
        printf("loadbitmap - bitcount failed = %d\n", infoHeader->biBitCount);
        return NULL;
    }

    fseek(bitmapFile, fileHeader->bfOffBits, SEEK_SET);

    int nBytes = infoHeader->biWidth * infoHeader->biHeight * 3;
    pixelBuffer = new unsigned char[nBytes];
    fread(pixelBuffer, sizeof(unsigned char), nBytes, bitmapFile);

    fclose(bitmapFile);

    for (int i = 0; i < nBytes; i += 3)
    {
        unsigned char tmp = pixelBuffer[i];
        pixelBuffer[i] = pixelBuffer[i + 2];
        pixelBuffer[i + 2] = tmp;
    }

    printf("loadbitmap - loaded %s w=%d h=%d bits=%d\n", filename, infoHeader->biWidth, infoHeader->biHeight, infoHeader->biBitCount);
}

#endif

我使用这个纹理如下:

GLuint texture = setup_texture("OBJFiles/Body.bmp");
        glBindTexture(GL_TEXTURE_2D, texture);
        glUseProgram(shaderProgram);
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 6498);
        glBindVertexArray(0);

根据发布的代码,错误消息loadbitmap - bitcount failed = 8表明加载的图像使用每像素8位,可能是8位灰度图像。

BITMAPINFOHEADER structure (wingdi.h)biBitCount 成员的文档说:

biBitCount

Specifies the number of bits per pixel (bpp). For uncompressed formats, this value is the average number of bits per pixel. For compressed formats, this value is the implied bit depth of the uncompressed image, after the image has been decoded.

因此,请尝试加载颜色深度为 24 bpp(每个颜色通道 8 位)的 RGB 位图文件。

为了使其与原始文件一起使用,可以在图像编辑器中将灰度图像转换为所需格式(例如 Gimp). Alternatively, the bitmap loader code could be modified to accept grayscale images (related topic: )。