gpt4 book ai didi

c++ - 在 C++ 中读取 .bmp 文件

转载 作者:可可西里 更新时间:2023-11-01 17:17:06 29 4
gpt4 key购买 nike

我正在尝试加载一个 bmp 文件以便在 opengl 中重复使用它。我通过谷歌找到了一些关于如何加载 bmp 文件的代码。我拿了这段代码并在我的项目中放入了一个类位图。这个类离结束还很远,但文件头的读取已经出错了。读取 INFOHEADER 和 FILEHEADER 的字节后,我的结构中没有正确的值。一些想法?

//
// Bitmap.h
//

#ifndef LaserMaze_Bitmap_h
#define LaserMaze_Bitmap_h

typedef struct /**** BMP file header structure ****/
{
unsigned short bfType; /* Magic number for file */
unsigned int bfSize; /* Size of file */
unsigned short bfReserved1; /* Reserved */
unsigned short bfReserved2; /* ... */
unsigned int bfOffBits; /* Offset to bitmap data */
} BITMAPFILEHEADER;

# define BF_TYPE 0x4D42 /* "MB" */

typedef struct /**** BMP file info structure ****/
{
unsigned int biSize; /* Size of info header */
int biWidth; /* Width of image */
int biHeight; /* Height of image */
unsigned short biPlanes; /* Number of color planes */
unsigned short biBitCount; /* Number of bits per pixel */
unsigned int biCompression; /* Type of compression to use */
unsigned int biSizeImage; /* Size of image data */
int biXPelsPerMeter; /* X pixels per meter */
int biYPelsPerMeter; /* Y pixels per meter */
unsigned int biClrUsed; /* Number of colors used */
unsigned int biClrImportant; /* Number of important colors */
} BITMAPINFOHEADER;

/*
* Constants for the biCompression field...
*/

# define BI_RGB 0 /* No compression - straight BGR data */
# define BI_RLE8 1 /* 8-bit run-length compression */
# define BI_RLE4 2 /* 4-bit run-length compression */
# define BI_BITFIELDS 3 /* RGB bitmap with RGB masks */

typedef struct /**** Colormap entry structure ****/
{
unsigned char rgbBlue; /* Blue value */
unsigned char rgbGreen; /* Green value */
unsigned char rgbRed; /* Red value */
unsigned char rgbReserved; /* Reserved */
} RGBQUAD;

class Bitmap {
public:
Bitmap(const char* filename);
~Bitmap();
RGBQUAD* pixels;
BITMAPFILEHEADER fh;
BITMAPINFOHEADER ih;

private:

};

#endif

中国共产党

//  Bitmap.cpp
//

#include <iostream>
#include <stdio.h>

#include "Bitmap.h"

Bitmap::Bitmap(const char* filename) {
FILE* file;
file = fopen(filename, "rb");

std::cout << sizeof(BITMAPFILEHEADER) << std::endl;

if(file != NULL) { // file opened
BITMAPFILEHEADER h;
size_t x = fread(&h, sizeof(BITMAPFILEHEADER), 1, file); //reading the FILEHEADER

std::cout << x;
fread(&this->ih, sizeof(BITMAPINFOHEADER), 1, file);

fclose(file);
}
}

最佳答案

header 需要 2 字节对齐。

#pragma pack(2) // Add this

typedef struct
{
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BITMAPFILEHEADER;

#pragma pack() // and this

关于c++ - 在 C++ 中读取 .bmp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8836017/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com