Home  >  Q&A  >  body text

如何用C++进行位图RGB读写操作

我想通过C语言打开指定位图的RGB值信息,类似Matlab中imread函数功能.由于无法将像素一一映射成控制台字符按原图显示,我通过重写该图看是否与原图一致验证读位图操作是否成功.结果写出来的位图无法打开.我对比了一下,占用存储空间也比原文件小一点,我猜测是自己对此类型图片的存储结构不了解导致的错误.以下是读写位图操作的代码,请各位指点:

#include<stdlib.h>
#include<iostream>
#include<windows.h> 
//文件路径 
#define READPATH "c:\\Users\\asus\\Desktop\\000.bmp"
#define WRITEPATH "c:\\Users\\asus\\Desktop\\0.bmp"
//位图宽和高 
#define W 72
#define H 1980

using namespace std;

int main()
{
    BITMAPFILEHEADER bitFile;
    BITMAPINFOHEADER bitInfo;
    RGBQUAD rgbQuad;
    BYTE b[W][H];
    FILE *fp;
//读文件 
    if(!(fp = fopen(READPATH, "r")))
    {
        printf("Error1!");
        exit(0);
    }
//读文件头 
    if(!(fread(&bitFile, sizeof(bitFile), 1, fp) && fread(&bitInfo, sizeof(bitInfo), 1, fp) && fread(&rgbQuad, sizeof(rgbQuad), 1, fp)))
    {
        fclose(fp);
        printf("Error2!");
        exit(0);
    }
//读数据 
    if(!(fread(&b, sizeof(BYTE), W * H, fp)))
    {
        fclose(fp);
        printf("Error3!");
        exit(0);
    }
    fclose(fp);
//写文件 
    if(!(fp = fopen(WRITEPATH, "w+")))
    {
        printf("Error4!");
        exit(0);
    }
    if(!(fwrite(&bitFile, sizeof(bitFile), 1, fp) && fwrite(&bitInfo, sizeof(bitInfo), 1, fp) && fwrite(&rgbQuad, sizeof(rgbQuad), 1, fp)))
    {
        fclose(fp);
        printf("Error5!");
        exit(0);
    }
    if(!(fwrite(&b, sizeof(BYTE), W * H, fp)))
    {
        fclose(fp);
        printf("Error6!");
        exit(0);
    }
    fclose(fp);
    cout<<endl<<"Succeed!"<<endl;
    return 0;
}

//经回答的朋友提醒我补充一下,以上代码是针对我测试用的8位位图的,不具有普适性.

怪我咯怪我咯2715 days ago650

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:24:51

    I haven’t looked at the code carefully yet, so I’ll leave a hole first. . .

    Let me first talk about the results at a glance. When I saw the sentence fwrite(&b, sizeof(BYTE), W * H, fp), is the bmp of the question subject 256 colors? If it is 24-bit, it should be W*H*3. In addition, there is align in the bitmap file in bmp format, so the size of the data block should not be passed through W*H*(位深度/3), but obtained by reading the information in the file header

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:24:51

    I wrote one in C before
    https://github.com/luckyScrip...
    You can check on Wikipedia what things are stored in the binary of this format~

    reply
    0
  • Cancelreply