PictureEx类能支持bmp、jpg、gif、png等格式图片的显示,同时也提供了3中导入图片数据的接口:
第一种:以文件名形式直接导入图片
// i.e. Load(_T("mypic.gif"));
BOOL Load(LPCTSTR szFileName);
第二种:从全局内存区导入图片
// loads a picture from a global memory block (allocated by GlobalAlloc)
// Warning: this function DOES NOT free the global memory, pointed to by hGlobal
BOOL Load(HGLOBAL hGlobal, DWORD dwSize);
第三中:从MFC等导入程序的资源中导入
// loads a picture from a program resource
// i.e. Load(MAKEINTRESOURCE(IDR_MYPIC),_T("GIFTYPE"));
BOOL Load(LPCTSTR szResourceName,LPCTSTR szResourceType);
当然,这里我们选用第2种方式。
废话少说,大家看看,一起学习
发送端发送代码:
void SendData()
{
CFile file;
if(!file.Open(filename,CFile::modeRead | CFile::shareDenyWrite))
{
AfxMessageBox("打开文件失败");
return;
}
image.dwsize = dwSize = file.GetLength();
HGLOBAL hGlobal;
hGlobal = GlobalAlloc(GMEM_MOVEABLE | GMEM_NODISCARD,dwSize); //分配内存区
if(!hGlobal)
{
GetError();
AfxMessageBox("分配内存空间失败");
file.Close();
return ;
}
//锁定分配内存块
char *pData = reinterpret_cast<char*>(GlobalLock(hGlobal)); //reinterpret_cast是强制类型转换
if(!pData)
{
GetError();
file.Close();
GlobalFree(hGlobal);
AfxMessageBox("锁内存失败");
return;
}
try
{
file.Read(pData,dwSize); //这个很重要哦
}catch(CFileException e)
{
GlobalFree(hGlobal);
file.Close();
AfxMessageBox("读取文件失败");
}
file.Close();
sendto(cltsocket,pData,dwSize,0,(SOCKADDR*)&srvaddr,sizeof(SOCKADDR));
GetError();
GlobalFree(hGlobal);
GlobalUnlock(hGlobal);
closesocket(cltsocket);
}
接收端接收线程:
UINT ThreadFun2(LPVOID pThreadParam)//用来接收数据
{
while(1)
{
CChBmpDlg *pdlg = (CChBmpDlg*)pThreadParam;
// pdlg->SetDlgItemText(IDC_STATIC_TIME,"收到图片数据");
// char recvbuf[55815];
// struct ChImage image;
char *pData;
SOCKADDR_IN cltaddr;
int len = sizeof(cltaddr);
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE | GMEM_NODISCARD,45000);//分配内存空间(字节),类似于new、malloc
// pdlg->GetError();
pData = reinterpret_cast<char*>(GlobalLock(hGlobal));
recvfrom(srv_socket,pData,45000,0,(SOCKADDR*)&cltaddr,&len);
pdlg->SetDlgItemText(IDC_STATIC_TIME,"收到图片数据");
pdlg->m_Show.Load(hGlobal,45000);
pdlg->m_Show.Draw(1.0);
GlobalFree(hGlobal);
GlobalUnlock(hGlobal);
}
return 0;
}