如何解决我应该使用什么I / O函数来写入.bmp文件?
| 我看到的示例代码似乎使用了标准的C文件输出功能,但是我想用C ++来实现。 我尝试使用fsteam函数执行此操作,但是根本没有数据写入.bmp文件。 到目前为止,我已经尝试过标准的<<,放置和编写,但这些都不起作用。如果我使用十六进制编辑器将其打开,则该文件仍为空。 这很奇怪,因为输入功能可以正常工作。 这是我用来测试其是否正常工作的一部分代码:output.open(\"WHITE.bmp\");
output.put(\'B\'); // this doesn\'t seem to work,the file is empty when I open it in a hex editor.
output.put(\'M\');
其余代码:
#include <iostream>
#include <fstream>
using namespace std;
typedef unsigned char byte;
typedef unsigned short dbyte;
struct BMPINFO
{
int width;
int height;
};
int main()
{
ifstream sourcefile;
ofstream output;
int threshold = 150;
sourcefile.open(\"RED.bmp\");
if(sourcefile.fail())
{
cout << \"Could not open RED.bmp\" << endl;
return 1;
}
if(sourcefile.get() == \'B\')
{
if(sourcefile.get() == \'M\')
{
cout << \"RED.bmp is a valid .bmp file\" << endl;
}
}
else
{
cout << \"RED.bmp is not a valid .bmp file\" << endl;
return 1;
}
BMPINFO image;
// seeks to bitmap width,this file is little end in.
sourcefile.seekg (0x12,ios::beg);
unsigned int i = (unsigned)sourcefile.get();
i += (unsigned)sourcefile.get() << 8;
image.width = i;
cout << \"The width of the image is: \" << image.width << endl;
sourcefile.seekg (0x16,ios::beg);
i = sourcefile.get();
i += (unsigned)sourcefile.get() << 8;
image.height = i;
cout << \"The height of the image is: \" << image.height << endl;
int loc_pixels;
sourcefile.seekg (0x0A,ios::beg);
loc_pixels = sourcefile.get();
cout << \"Location of pixel array is: \" << loc_pixels << endl;
output.open(\"WHITE.bmp\");
output.put(\'B\'); // this doesn\'t seem to work,the file is empty when I open it in a hex editor.
output.put(\'M\');
if(output.bad())
{
cout << \"the attempt to output didn\'t work\" << endl;
return 1;
}
sourcefile.seekg(loc_pixels,ios::beg);
char data[30000];
output.close();
return 0;
}
我应该使用特殊功能输出到此.bmp文件吗?
编辑-添加了更多代码,尽管其中大多数与文件输出无关
解决方法
您在此代码中有一个缓冲区溢出错误:
char data[30000]; // Prepare file for usage -- just copy one thing from the file to the other
sourcefile.read(data,image.height * image.width );
您正在读取image.height*image.width
字节,并尝试将它们调整为30000
字节。您应该对代码进行结构设计,以使这两个数字相关联。
尝试这个:
std::vector<char> data(image.height * image.width);
sourcefile.read(&data[0],data.size());
, 这里有一个很好的描述。
ofstream myfile;
myfile.open(\"WHITE.bmp\",ios::out | ios::binary); // opening in binary mode
myfile << \'B\';
myfile << \'M\';
myfile.close();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。