C语言读BMP图片

#include<windows.h>  //包含相关bmp格式的定义结构
#include<stdio.h>
#include<stdlib.h>

int bmpWidth;  //bmp图片宽度(像素)
int bmpHeight;  //bmp图片高度(像素)
RGBQUAD* pColorTable;  //调色板数组(真彩色时不用)
int  biBitCount;  //每像素所占的字节

/*************************************************************
* 名称:Read_BMP
* 功能:读bmp图像,返回读出的16进制数组
* 入口参数:bmpfilename:bmp图片名
* 出口参数:无 
**************************************************************/    
unsigned char* Read_BMP(const char* bmpfilename)
{
    unsigned char*  pBmpBuf;  //存储缓冲区
    FILE* fp = fopen(bmpfilename,"rb");  //二进制制度打开
    if(fp == NULL) 
    {
        printf("Can not open this file");
        return 0;
    }
    fseek(fp,sizeof(BITMAPFILEHEADER),0);  //跳过BMP头
    BITMAPINFOHEADER infoheader;
    fread(&infoheader,sizeof(BITMAPINFOHEADER),1,fp);  //读bmp图片信息
    bmpWidth = infoheader.biWidth;
    bmpHeight = infoheader.biHeight;
    biBitCount = infoheader.biBitCount;
    int line_Byte = (bmpWidth*biBitCount/8+3)/4*4;  //每行所占字节数
    if(biBitCount == 8)
    {
        pColorTable = new RGBQUAD[256];
        fread(pColorTable,sizeof(RGBQUAD),256,fp);
    }
    pBmpBuf = new unsigned char [line_Byte*bmpHeight];  //开辟存储区
    fread(pBmpBuf,1,line_Byte*bmpHeight,fp);
    fclose(fp);  //关闭文件
    return pBmpBuf;
}

/*************************************************************
* 名称:main
* 功能:测试函数
* 入口参数:无
* 出口参数:无 
**************************************************************/    
int main()
{
    unsigned char* Buffer=Read_BMP("1.bmp");  //读bmp图片
    FILE* fp = fopen("test.txt","wb");  
    fwrite(Buffer,1,(bmpWidth*biBitCount/8+3)/4*4*bmpHeight,fp);  //将读出的图片数据写入test.txt  
    return 0;
}

存入文本文件的16进制数据是乱码的,需要用16进制编辑工具读出;而且默认bmp图片读图书序是从左下角开始的,这样在在TFT上显示的时候,需要注意先从左下角开始扫描,或者先将数据转换成左上角开始的顺序。

posted on 2015-08-26 14:36  jianqi2010  阅读(949)  评论(0编辑  收藏  举报

导航