读取位图文件

位图由位图文件头、位图信息头、颜色表、位图像素数据四部分组成,网上关于位图文件结构介绍的资料很多,这里就不再赘述。

下面我们主要介绍一下位图文件的读取。

一. 读取位图文件

1. 头文件中添加如下变量

    CString strFileName;        //打开文件名
    BITMAPFILEHEADER bmfHeader; //位图文件头
    BITMAPINFOHEADER bmiHeader; //位图信息头
    void* pimage;               //位图数据
    RGBQUAD* pRgbQuad;          //颜色表
    long number_image           //位图数据大小

2. 添加打开消息响应函数OnFileOpen()

    //弹出打开对话框

    CFileDialog dlg(TRUE,TEXT("BMP"),0,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,TEXT("位图文件(*.BMP)|*.BMP||"),this);
    dlg.m_ofn.lpstrTitle = "Open Bitmap";
    if(dlg.DoModal() != IDOK)
        return;

    //打开位图文件

    CFile file;
    strFileName=dlg.GetPathName();
    if(file.Open(strFileName, CFile::modeRead | CFile::shareDenyNone, NULL) == 0)
    {
        AfxMessageBox("File open failed.");
        return;
    }    

    //读取位图文件头

    file.Read(&bmfHeader, sizeof(bmfHeader));
    if(bmfHeader.bfType != (*(WORD*)"BM"))    //0x4d42
    {
        AfxMessageBox("File type error.");
        return;
    }
    if(file.GetLength() != bmfHeader.bfSize)
    {
        AfxMessageBox("File is demaged.");
        return;
    }

    //读取位图信息头

    file.Read(&bmiHeader, sizeof(bmiHeader));

    //读取颜色表

    if(bmiHeader.biBitCount == 8)    //256色位图
    {
        pRgbQuad = new RGBQUAD[256];
        file.Read(pRgbQuad, sizeof(RGBQUAD)*256);
    }
    else if(bmiHeader.biBitCount != 24)
    {
        AfxMessageBox("Only 24bit and 8bit could be opened.");
        return;
    }

    //读取位图数据

    int lineByte = (bmiHeader.biWidth*bmiHeader.biBitCount/8+3)/4*4;
    number_image = lineByte*(bmiHeader.biHeight);
    pimage = new BYTE[number_image];
    file.Read(pimage, number_image);
    file.Close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值