前端有哪些技能:怎样用VC++实现对24位bmp图像的打开和显示(bmp图片假定放在D盘picture文件夹内)

来源:百度文库 编辑:中财网 时间:2024/04/29 23:15:34
24位位图在VC++中需要三个结构来存储:
BITMAPFILEHEADER:文件信息头
LPBITMAPINFOHEADER:位图信息头指针
LPBYTE:像素数据指针

假设你的图片名为:“图片.bmp”。

1、你用VC++建立一个MFC(exe)工程,命名为“My”,在弹出的“MFC应用程序向导-步骤1”中选“单文档”,然后点“完成”->“确定”。

2、在“MyView.h”文件中找到代码“CMyDoc* GetDocument();”在其下方添加如下代码:
BITMAPINFOHEADER bmih;
LPBYTE pBits;
BOOL Read(char* s);

3、然后打开“MyView.cpp”文件,在最下面写如下代码:
BOOL CMyView::Read(char* s)
{
CFile file;
BITMAPFILEHEADER bmfh;

//打开文件
if(!file.Open(s,CFile::modeRead))
{
  AfxMessageBox("File cannot open!");
  return FALSE;
}

//读文件信息头
file.Read( (LPVOID)&bmfh, sizeof(bmfh) );
if(bmfh.bfType != 0x4d42)
{
  AfxMessageBox("This is not a bmp file!");
  return FALSE;
}

//读位图信息头
int infoSize = bmfh.bfOffBits - sizeof(bmfh);
bmih = (LPBITMAPINFOHEADER)new BYTE[infoSize];
file.Read( (LPVOID)bmih, infoSize);
if(bmih->biBitCount!=24)
{
  AfxMessageBox("The number of colors is not valid!");
  return FALSE;
}

//读图像数据
pBits = new BYTE[bmih->biSizeImage];
file.Read( (LPVOID)pBits, bmih->biSizeImage);

return TRUE;
}

4、往上找,找到构造函数:CMyView::CMyView()
在其中添加代码:
Read("d:\\picture\\图片.bmp");

5、往下找,找到OnDraw函数,在该函数的第三行添加代码:
if(bmih && pBits)
{
  ::StretchDIBits(pDC->GetSafeHdc(),0,0,bmih->biWidth,bmih->biHeight,0,0,bmih->biWidth,bmih->biHeight,pBits,(LPBITMAPINFO)bmih,DIB_RGB_COLORS,SRCCOPY);
}

运行即可。我已试过,可以打开并显示。希望你一步一步照做,代码不要写错!

 ×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

////////////////////////////////////////////

FILE *fopen( const char *filename, const char *mode );mode一般为"r"或者"w",Opens for reading. Opens an empty file for writing.

fopen("G:\\test.txt",'w'); 可行

filename = dlg.GetPathName(); 可以获得路径

///////////////////////////////////////////////////////////

fread: Reads data from a stream 从一个流中读数据

Pointer to FILE structure

int fread(void *buffer, int size, int count, FILE *stream);

  参 数:用于接收数据的地址(字符型指针)(buffer) Storage location for data

  单个元素的大小(size) Item size in bytes

  元素个数(count)Maximum number of items to be read

  提供数据的文件指针(stream)

  返回值:成功读取的元素个数

////////////////////////////////////////////

 

打开文件后读取bmp文件中的数据:

FILE *fp=fopen(filename,"r"); //按照filename的路径打开文件

BITMAPFILEHEADER fileheader;
BITMAPINFO info;

fread(&fileheader,sizeof(fileheader),1,fp); //读取头文件信息

if(fileheader.bfType!=0x4D42)
{
   pDC->TextOut(100,200,"无位图文件 请选择位图文件");
   fclose(fp);
   return ;
}

fread(&info.bmiHeader, sizeof(BITMAPINFOHEADER), 1, fp);      /*读取信息头*/
long width=info.bmiHeader.biWidth;
long height=info.bmiHeader.biHeight;                   //位图高度及宽度
UCHAR *buffer=new UCHAR[info.bmiHeader.biSizeImage];   //位图的大小
fseek(fp,fileheader.bfOffBits,0);                      //重定位流上的文件指针,接下来的操作将从新位置开始
fread(buffer,info.bmiHeader.biSizeImage,1,fp);