在位图头文件中写入字节值

时间:2015-05-30 12:10:50

标签: c++ bitmap hex

我试图将位图标头写入文件。目前,我只想写没有任何像素数据的标题。我基于thisthisthis上的值。我有以下函数用于组合标准的,未压缩的24位RGB位图头作为uint8_t:

uint8_t* make_rgb24_bmp_header(int data_size, int width, int height)
    {
        uint8_t* ret = new uint8_t[BITMAP_HEADER_SIZE];

        //signature
        ret[0] = 'B';
        ret[1] = 'M';

        //2-3-4-5
        write_32bit_num_to_data(ret + 2, data_size); //file size in bytes as hexadecimal

        ret[6] = 0;
        ret[7] = 0;
        ret[8] = 0;
        ret[9] = 0;
        //specifies the starting offset of the image - 54 bytes in.
        ret[10] = 0x36;
        ret[11] = 0;
        ret[12] = 0;
        ret[13] = 0;
        //specifies header size - 40 bytes
        ret[14] = 28;
        ret[15] = 0;
        ret[16] = 0;
        ret[17] = 0;

        //18,19,20,21 - image width
        write_32bit_num_to_data(ret + 18, width);
        //20,23,24,25 - image height
        write_32bit_num_to_data(ret + 22, height);

        //planes - 1
        ret[26] = 1;
        ret[27] = 0;
        //bpp - 24
        ret[28] = 18;
        ret[29] = 0;
        //compression - 0
        ret[30] = 0;
        ret[31] = 0;
        ret[32] = 0;
        ret[33] = 0;

        //34,35,36,37
        write_32bit_num_to_data(ret + 34, data_size); //compressed size - no compression here, so same as data_size
        //38,39,40,41
        write_32bit_num_to_data(ret + 38, 2835); //Horizontal resolution in pixels per meter
        //42,43,44,45
        write_32bit_num_to_data(ret + 42, 2835); //Vertical resolution in pixels per meter

        //number of colors - not needed as we're not using a color palette
        ret[46] = 0;
        ret[47] = 0;
        ret[48] = 0;
        ret[49] = 0;

        //important colors - not needed
        ret[50] = 0;
        ret[51] = 0;
        ret[52] = 0;
        ret[53] = 0;

        return ret;
    }

我以下列方式保存:

int main(int argc, char** argv)
{

    uint8_t* header = utils::make_rgb24_bmp_header(1244214, 720, 576);

    ofstream out;

    out.open("sample_header", ios::out | ios::binary);

    out.write((char*)&header, 54);

    out.close();

    return 0;
}

我希望文件的前两个字节为44 4d,但是当我在Bless中打开输出文件时,它们会显示为F0 E0。很明显,我已经错过了一些必要的东西(我也可以看到其余的值是不正确的),并且理解我前两个字节出错的地方应该可以帮助我完成其余的工作。我如何获得我期望的输出?

1 个答案:

答案 0 :(得分:2)

您将错误的值传递给out.write:

out.write((char*)header, 54);

通过将其作为&标头传递,您试图写出存储指针的值而不是指向的位置(以及数据所在的位置)。