c++读取bmp图片详解

来源:互联网 发布:mysql商品表设计 编辑:程序博客网 时间:2024/05/26 16:01

先介绍几个会用到的函数。

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;}




0 1
原创粉丝点击