您的位置:首页 > 编程语言 > C语言/C++

c++读取bmp图片详解

2014-12-01 23:54 579 查看
先介绍几个会用到的函数。

1、FILE * fopen(const
char * path,const char * mode);

path是字符串类型的bmp图片路径;mode读取方式,等下回用到"rb",读写打开一个二进制文件,允许读写数据,文件必须存在。

2、int fseek(FILE *stream, long offset, int fromwhere);

函数设置文件指针stream的位置,stream指向以fromwhere为基准,偏移offset个字节的位置。

3、size_t fread
( void *buffer, size_t size, size_t count, FILE *stream)
;

从stream中读取count个单位大小为size个字节,存在buffer中。

在贴个代码:

#include <iostream>
#include <windows.h>
#include <stdio.h>

using namespace std;
int bmpwidth,bmpheight,linebyte;
unsigned char *pBmpBuf;  //存储图像数据

bool readBmp(char *bmpName)
{
    FILE *fp;
    if( (fp = fopen(bmpName,"rb")) == NULL)  //以二进制的方式打开文件
    {
        cout<<"The file "<<bmpName<<"was not opened"<<endl;
        return FALSE;
    }
    if(fseek(fp,sizeof(BITMAPFILEHEADER),0))  //跳过BITMAPFILEHEADE
    {
        cout<<"跳转失败"<<endl;
        return FALSE;
    }
    BITMAPINFOHEADER infoHead;
    fread(&infoHead,sizeof(BITMAPINFOHEADER),1,fp);   //从fp中读取BITMAPINFOHEADER信息到infoHead中,同时fp的指针移动
    bmpwidth = infoHead.biWidth;
    bmpheight = infoHead.biHeight;
    linebyte = (bmpwidth*24/8+3)/4*4; //计算每行的字节数,24:该图片是24位的bmp图,3:确保不丢失像素

    //cout<<bmpwidth<<" "<<bmpheight<<endl;
    pBmpBuf = new unsigned char[linebyte*bmpheight];
    fread(pBmpBuf,sizeof(char),linebyte*bmpheight,fp);
    fclose(fp);   //关闭文件
    return TRUE;
}
void solve()
{
    char readFileName[] = "nv.BMP";
    if(FALSE == readBmp(readFileName))
        cout<<"readfile error!"<<endl;
}

int main()
{
    solve();
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: