我一直在尝试用ifstream读取一个bmp文件,但是它在没有调试的情况下工作得很好,当我在调试模式下运行它时,它失败了。一开始,我读取了54字节的信息,以获得图片的高度和宽度,不幸的是,在调试模式下,它们是-858993460,所以每次图片的整个大小都会溢出,所以我得到了一个糟糕的分配错误。我使用的是VS 2013,有人能帮我解决这个问题吗?
unsigned char* readBMP(char* filename)
{
int i;
char info[54];
std::ifstream ifs(filename, std::ifstream::binary);
ifs.read(info, 54);
// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];
int size = 3 * width * height;
char* data = new char[size]; // allocate 3 bytes per pixel
ifs.read(data, size);
ifs.close();
return (unsigned char*)data;
}发布于 2015-05-19 06:20:58
我猜你打开文件失败了,所以你的读取一定失败了。
你可以查看:if (ifs.is_open()) { /* good*/}
您还可以查看:if(ifs.read(...)){/*good*/}
尝试以下代码:
unsigned char* readBMP(char* filename)
{
int i;
char info[54];
std::ifstream ifs(filename, std::ifstream::binary);
if(!ifs.is_open()){
std::cerr<<" failed to open file"<<std::endl;
return NULL;
}
if(!ifs.read(info, 54)) {
std::cerr<<" failed to read from file"<<std::endl;
return NULL;
}
// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];
int size = 3 * width * height;
char* data = new char[size]; // allocate 3 bytes per pixel
ifs.read(data, size);
ifs.close();
return (unsigned char*)data;
}https://stackoverflow.com/questions/30313409
复制相似问题