您的位置:首页 > 其它

BMP显示和保存

2012-07-27 15:05 148 查看
struct Pixel

{

UCHAR B;

UCHAR G;

UCHAR R;

};

Pixel* Img = new Pixel[RImg_Hpixles*RImg_Vpixles];

BITMAPINFO *m_pBMI = (BITMAPINFO*)new char[sizeof(BITMAPINFO) + sizeof(RGBQUAD) * (255)];

CDC* pDC=GetDC(); //获得当前窗口句柄

CRect rcBmp;

GetDlgItem(IDC_Pic)->GetWindowRect(rcBmp); //IDC_Pic是picture控件ID

ScreenToClient(&rcBmp);

m_pBMI->bmiHeader.biBitCount = 24;// 24位图像数据结构,需要用3个BYTE的数据类型构造

m_pBMI->bmiHeader.biClrImportant = 0;

m_pBMI->bmiHeader.biCompression = 0;

m_pBMI->bmiHeader.biHeight = -(image_rawHeight/2); //负号使显示的图像不出现倒置情况,因为图像是自底向上填写的

m_pBMI->bmiHeader.biClrUsed =256;//0;

m_pBMI->bmiHeader.biPlanes = 1;

m_pBMI->bmiHeader.biSize = 40;

m_pBMI->bmiHeader.biSizeImage = (image_rawHeight/2)*(image_rawWidth/2)*3;//

m_pBMI->bmiHeader.biWidth = image_rawWidth/2;

m_pBMI->bmiHeader.biXPelsPerMeter = 0;

m_pBMI->bmiHeader.biYPelsPerMeter =0;

for(int i = 0; i<256;i++)

{

m_pBMI->bmiColors[i].rgbBlue =i;

m_pBMI->bmiColors[i].rgbGreen =i;

m_pBMI->bmiColors[i].rgbRed =i;

m_pBMI->bmiColors[i].rgbReserved = 0;

}

SetDIBitsToDevice(pDC->m_hDC,rcBmp.left,rcBmp.top,rcBmp.Width(),rcBmp.Height(),0,0,0,image_rawHeight/2,Img,m_pBMI,DIB_RGB_COLORS);

struct Pixel

{

BYTE gray[3];

};

void Write2BMP(Pixel *pixarr, int xsize, int ysize, CHAR *filename)

{

unsigned char header[54] = {

0x42, 0x4d, 0, 0, 0, 0, 0, 0, 0, 0,

54, 0, 0, 0, 40, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 1, 0, 24, 0,

0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0

};

int i;

int j;

long file_size = (long)xsize * (long)ysize * 3 + 54;

header[2] = (unsigned char)(file_size &0x000000ff);

header[3] = (file_size >> 8) & 0x000000ff;

header[4] = (file_size >> 16) & 0x000000ff;

header[5] = (file_size >> 24) & 0x000000ff;

long width;

if(!(xsize%4)) width=xsize;

else width= xsize+(4-xsize%4); //如不是4的倍数,则转换成4的倍数

header[18] = width & 0x000000ff;

header[19] = (width >> 8) &0x000000ff;

header[20] = (width >> 16) &0x000000ff;

header[21] = (width >> 24) &0x000000ff;

long height = -ysize;

header[22] = (height &0x000000ff);

header[23] = ((height >> 8) &0x000000ff);

header[24] = ((height >> 16) &0x000000ff);

header[25] = ((height >> 24) &0x000000ff);

CHAR fname_bmp[128];

sprintf(fname_bmp, "%s.bmp", filename);

FILE *fp;

fp = fopen(fname_bmp, "wb");

fwrite(header, sizeof(unsigned char), 54, fp);

Pixel zero={0,0,0}; //不足字节,用zero填充

for(INT i=0;i<xsize*ysize;i++)

{

fwrite(pixarr+i, sizeof(Pixel),1, fp);

}

/*

for(j=0;j<ysize;j++)

{

if(!(xsize%4)){

for(i=0;i<xsize;i++){

fwrite(pixarr+i, sizeof(Pixel),1, fp);

}

}

else

{

for(i=0;i<xsize;i++){

fwrite(pixarr+i, sizeof(Pixel),1, fp);

}

for(i=xsize;i<xsize+(4-xsize%4);i++){

fwrite(&zero, sizeof(Pixel),1, fp);

}

}

}

*/

fclose(fp);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: