保存图片到磁碟(vc++)

来源:互联网 发布:域名投资现在晚了吗 编辑:程序博客网 时间:2024/05/09 15:39

void WBMP2HD(CDC* pDC,LPCTSTR FileName,int nwidth=0,int nheight=0)
{
    //CDC* pDC=CDC::FromHandle(::GetDC(NULL));
 
 int bitspixel =pDC->GetDeviceCaps(BITSPIXEL);
 int width=nwidth,height=nheight;
 if( nwidth==0)
  width=pDC->GetDeviceCaps(HORZRES);
 if (nheight==0)
  height=pDC->GetDeviceCaps(VERTRES);

 CDC MemDC;
 MemDC.CreateCompatibleDC(pDC);
    CBitmap bitmap,*oldbitmap;
 bitmap.CreateCompatibleBitmap(pDC,width,height);
 oldbitmap = MemDC.SelectObject(&bitmap);
 MemDC.BitBlt(0,0,width,height,pDC,0,0,SRCCOPY);
 
 BITMAP bmp;
 bitmap.GetBitmap(&bmp);
    //获得位图信息
   
 FILE *fp = fopen(FileName, "w+b");

    BITMAPINFOHEADER bih = {0};//位图信息头
    bih.biBitCount = bmp.bmBitsPixel;//每个像素字节大小
    bih.biCompression = BI_RGB;
    bih.biHeight = bmp.bmHeight;//高度
    bih.biPlanes = 1;
    bih.biSize = sizeof(BITMAPINFOHEADER);
    bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;//图像数据大小
    bih.biWidth = bmp.bmWidth;//宽度
   
    BITMAPFILEHEADER bfh = {0};//位图文件头
    bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位图数据的偏移量
    bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;//文件总的大小
    bfh.bfType = (WORD)0x4d42;
   
    fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);//写入位图文件头
   
    fwrite(&bih, 1, sizeof(BITMAPINFOHEADER), fp);//写入位图信息头
   
    byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];//申请内存保存位图数据

    GetDIBits(MemDC.m_hDC, (HBITMAP) bitmap.m_hObject, 0, height, p,
        (LPBITMAPINFO) &bih, DIB_RGB_COLORS);//获取位图数据

    fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);//写入位图数据

    delete [] p;

    fclose(fp);

    MemDC.SelectObject(oldbitmap);

}

调用的时候如果要保存当前的桌面则可以这样写:

 CDC* pDC=CDC::FromHandle(::GetDC(NULL));
   WBMP2HD(pDC,"c://bbc.bmp",0,0));
   if( pDC->DeleteDC())
   {
    AfxMessageBox("ok");
   }
如果要保存当前的窗口图像则可以这样写:

CDC* pDC=CDC::FromHandle(::GetDC(this->GetSafeHwnd()));
CRect rect;
 GetClientRect(&rect);
 WBMP2HD(pDC,"c://bbc.bmp",rect.Width(),rect.Height());
   if( pDC->DeleteDC())
   {
    AfxMessageBox("ok");
   }

原创粉丝点击