将Byte数组保存成24位BMP

本文介绍了一个C++类CSaveByteToBmp,该类提供了从字节数组创建BMP图像的功能。它通过构建必要的BMP文件头和信息头来实现这一目标,并提供了一个方法用于将缓冲区数据保存为BMP文件。

直接上源代码:

#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;

class CSaveByteToBmp
{
public:
    bool SaveDIB2Bmp(int fileNum, const CString& BMPFileName, int iWidth, int iHeight, BYTE *pBuffer);
    void ConstructBih(int nWidth, int nHeight, BITMAPINFOHEADER& bih);
    void ContructBhh(int nWidth, int nHeight, BITMAPFILEHEADER& bhh);//add 2010-9-04;
protected:
private:

};

 

然后是cpp:

#include "stdafx.h"
#include "SaveByteToBmp.h"

//保存buffer到bmp文件
bool CSaveByteToBmp::SaveDIB2Bmp(int fileNum, const CString& BMPFileName, int iWidth, int iHeight, BYTE *pBuffer)
{
    BITMAPINFOHEADER bih;
    ConstructBih(iWidth, iHeight, bih);
    BITMAPFILEHEADER bhh;
    ContructBhh(iWidth, iHeight, bhh);

    int widthStep = (((iWidth * 24) + 31) & (~31)) / 8; //每行实际占用的大小(每行都被填充到一个4字节边界)
    int DIBSize = widthStep * iHeight;  //buffer的大小 (字节为单位)

    CFile file;
    try
    {
        if (file.Open(BMPFileName, CFile::modeWrite | CFile::modeCreate))
        {//写入文件

            file.Write((LPSTR)&bhh, sizeof(BITMAPFILEHEADER));
            file.Write((LPSTR)&bih, sizeof(BITMAPINFOHEADER));
            file.Write(pBuffer, DIBSize);
            file.Close();
            return true;
        }

    }
    catch (...)
    {
        MessageBox(NULL, _T("CSaveByteToBmp::SaveDIB2Bmp"), _T("tips"), MB_ICONERROR);
    }
    return false;
}



//构建BMP位图文件头
void CSaveByteToBmp::ContructBhh(int nWidth, int nHeight, BITMAPFILEHEADER& bhh) //add 2010-9-04
{
    int widthStep = (((nWidth * 24) + 31) & (~31)) / 8; //每行实际占用的大小(每行都被填充到一个4字节边界)
    bhh.bfType = ((WORD)('M' << 8) | 'B');  //'BM'
    bhh.bfSize = (DWORD)sizeof(BITMAPFILEHEADER)+(DWORD)sizeof(BITMAPINFOHEADER)+widthStep * nHeight;
    bhh.bfReserved1 = 0;
    bhh.bfReserved2 = 0;
    bhh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER)+(DWORD)sizeof(BITMAPINFOHEADER);

}


//构建BMP文件信息头
void CSaveByteToBmp::ConstructBih(int nWidth, int nHeight, BITMAPINFOHEADER& bih)
{
    int widthStep = (((nWidth * 24) + 31) & (~31)) / 8;

    bih.biSize = 40;       // header size
    bih.biWidth = nWidth;
    bih.biHeight = nHeight;
    bih.biPlanes = 1;
    bih.biBitCount = 24;     // RGB encoded, 24 bit
    bih.biCompression = BI_RGB;   // no compression 非压缩
    bih.biSizeImage = widthStep*nHeight * 3;
    bih.biXPelsPerMeter = 0;
    bih.biYPelsPerMeter = 0;
    bih.biClrUsed = 0;
    bih.biClrImportant = 0;

}

 

转载于:https://www.cnblogs.com/autumoonchina/p/4740018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值