bmp简单读取

· · 个人记录

由于 bmp 格式没有任何压缩算法,读取非常方便。

操作步骤:

  1. 将 png 等图片格式用画图打开,另存为 24 位位图
  2. 将 ea5j4H.BMP 处改成 bmp 图片的文件名
  3. 输出的 out.txt 就是每个像素的信息,每 3 行表示一个像素(rgb)
#include <math.h>
#include <iomanip>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;

unsigned char *pBmpBuf; //数据表指针

int width, height;
RGBQUAD *pColorTable; //颜色表指针

int biBitCount; //图像类型,每像素位数

bool readBmp(char *bmpName) {
    FILE *fp=fopen(bmpName,"rb");

    if(fp==0) return 0;

    //跳过位图文件头

    fseek(fp, sizeof(BITMAPFILEHEADER),0);

    //读取位图信息头

    BITMAPINFOHEADER head;
    fread(&head, sizeof(BITMAPINFOHEADER), 1,fp);
    width = head.biWidth;
    height = head.biHeight;
    biBitCount = head.biBitCount;
    int lineByte=(width * biBitCount/8+3)/4*4;

    // 申请空间并读取图片信息

    pBmpBuf=new unsigned char[lineByte * height];
    fread(pBmpBuf,1,lineByte * height,fp);
    fclose(fp);

    return 1;
}
int main() {

    char readPath[]="ea5j4H.BMP";
    readBmp(readPath);

    //输出图像的信息

    cout<<"width="<<width<<" height="<<height<<" biBitCount="<<biBitCount<<endl;


    int lineByte=(width*biBitCount/8+3)/4*4;
    int m=0,n=0;

    // 打开文件
    ofstream outfile("out.txt",ios::in|ios::trunc);

    if(!outfile) {
        cout<<"open error!"<<endl;
        exit(1);
    } else if(biBitCount==24) {

        for(int i=0; i<height; i++) {
            for(int j=0; j<width; j++) {
                for(int k=2; k>=0; k--){
                    m = *(pBmpBuf+i*lineByte+j*3+k);
                    outfile << m << endl;
                }
                n++;
            }

        }
        cout<<"size:"<<n<<endl;
        cout<<"----------------------------------------------------"<<endl;

    }else{
        cout<<"biBitCount != 24"<<endl;
        exit(1);
    }
}

网上抄的