c++ - 我应该使用什么 I/O 函数来写入 .bmp 文件?

标签 c++ bitmap fstream

我看到的示例代码似乎使用了标准的 C 文件输出函数,但我想用 C++ 来实现。

我尝试使用 fsteam 函数来执行此操作,但根本没有数据写入 .bmp 文件。

到目前为止,我已经尝试了标准的<<、put 和write,但都不起作用。如果我用十六进制编辑器打开它,文件仍然是空的。

这很奇怪,因为输入函数工作正常。

这是我用来测试它是否有效的一段代码:

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());

关于c++ - 我应该使用什么 I/O 函数来写入 .bmp 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6157561/

相关文章:

c++ - FFMPEG 和 DXVA2

android - 使用 quality=100 压缩的位图文件大小比原始文件大

C++文件输出只接受第一个字

c++ - 如何将json文件读入C++字符串

c++ - 第一个 fstream 程序

c++ - 你如何调试 MinGW 异常处理?

python - 导入 swig 生成的模块时,Python 提示缺少删除方法

android - Android OpenCV MatToBitmap导致黑色图像

c# - .NET C# - 位图和图像加载的图像都小于预期

C++ 读/写文本文件问题