我在读取 8 位灰度 bmp 时遇到问题。我能够从标题中获取信息并读取调色板,但我无法将像素值引用到调色板条目。在这里,我找到了如何读取像素数据,但实际上并没有找到如何在 bmp 带有调色板的情况下使用它。我是初学者。我的目标是一次只读取一行像素。
代码:
#include <iostream>
#include <fstream>
using namespace std;
int main(int arc, char** argv)
{ const char* filename="Row_tst.bmp";
remove("test.txt");
ofstream out("test.txt",ios_base::app);//file for monitoring the results
FILE* f = fopen(filename, "rb");
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the header
int width = *(int*)&info[18];
int height = *(int*)&info[22];
unsigned char palette[1024]; //read the palette
fread(palette, sizeof(unsigned char), 1024, f);
for(int i=0;i<1024;i++)
{ out<<"\n";
out<<(int)palette[i];
}
int paletteSmall[256]; //1024-byte palette won't be needed in the future
for(int i=0;i<256;i++)
{ paletteSmall[i]=(int)palette[4*i];
out<<paletteSmall[i]<<"\n";
}
int size = width;
//for(int j=0;j<height;j++)
{ unsigned char* data = new unsigned char[size];
fread(data, sizeof(unsigned char), size, f);
for(int i=0;i<width;i++)
{ cout<<"\n"<<i<<"\t"<<paletteSmall[*(int*)&data[i]];
}
delete [] data;
}
fclose(f);
return 0;
}
我在 test.txt 中得到的似乎很好——第一个值从 0 0 0 0 到 255 255 255 0(调色板),下一个值从 0 到 255(调色板小)。
问题是我无法将像素值引用到颜色表条目。我的应用程序崩溃了,症状可能表明它试图使用表格中一些不存在的元素。如果我理解正确,带有颜色表的 bmp 像素应该包含许多颜色表元素,所以我不知道为什么它不起作用。我请求你的帮助。