发现有两个很好的方法。
1.
void SaveIcon(HICON hIconToSave, LPCTSTR sIconFileName)
{
if(hIconToSave==NULL || sIconFileName==NULL)
return;
//warning: this code snippet is not bullet proof.
//do error check by yourself [masterz]
PICTDESC picdesc;
picdesc.cbSizeofstruct = sizeof(PICTDESC);
picdesc.picType = PICTYPE_ICON ;
picdesc.icon.hicon = hIconToSave;
IPicture* pPicture=NULL;
OleCreatePictureIndirect(&picdesc, IID_IPicture, TRUE,(VOID**)&pPicture);
LPSTREAM pStream;
CreateStreamOnHGlobal(NULL,TRUE,&pStream);
LONG size;
HRESULT hr=pPicture-> SaveAsFile(pStream,TRUE,&size);
char pathbuf[1024];
strcpy(pathbuf,sIconFileName);
CFile iconfile;
iconfile.Open(pathbuf, CFile::modeCreate|CFile::modeWrite);
LARGE_INTEGER li;
li.HighPart =0;
li.LowPart =0;
ULARGE_INTEGER ulnewpos;
pStream-> Seek( li,STREAM_SEEK_SET,&ulnewpos);
ULONG uReadCount = 1;
while(uReadCount> 0)
{
pStream-> Read(pathbuf,sizeof(pathbuf),&uReadCount);
if(uReadCount> 0)
iconfile.Write(pathbuf,uReadCount);
}
pStream-> Release();
iconfile.Close();
}
2.
BOOL WriteIconToICOFile(LPICONRESOURCE lpIR,LPCTSTR szFileName)
{
HANDLE hFile;
UINT i;
DWORD dwBytesWritten;
//open the file
if((hFile=CreateFile(szFileName,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL)) == INVALID_HANDLE_VALUE )
{
MessageBox(hWndMain, "Error Opening File for Writing ",szFileName,MB_OK);
return FALSE;
}
//Write the header
if(!WriteICOHeader(hFile,lpIR-> nNumImages))
{
MessageBox(hWndMain, "Error Writing ICO File ",szFileName,MB_OK);
CloseHandle(hFile);
return FALSE;
}
//Write the ICONDIRENTRY 's
for(i=0;i <lpIR-> nNumImages;i++)
{
ICONDIRENTRY ide;
//Convert internal format to ICONDIRENTRY
ide.bWidth=lpIR-> IconImages[i].Width;
ide.bHeight=lpIR-> IconImages[i].Height;
ide.bReserved=0;
ide.wPlanes=lpIR-> IconImages[i].lpbi-> bmiHeader.biPlanes;
ide.wBitCount=lpIR-> IconImages[i].lpbi-> bmiHeader.biBitCount;
if((ide.wPlanes*ide.wBitCount)> =8)
ide.bColorCount=0;
else
ide.bColorCount=1 < <(ide.wPlanes*ide.wBitCount);
ide.dwBytesInRes=lpIR-> IconImages[i].dwNumBytes;
ide.dwImageOffset=CalculateImageOffset(lpIR,i);
//Write the ICONDIRENTRY out to disk
if(!WriteFile(hFile,&ide,sizeof(ICONDIRENTRY),&dwBytesWritten,NULL))
return FALSE;
//Did we write a full ICONDIRENTRY?
if(dwBytesWritten!=sizeof(ICONDIRENTRY))
return FALSE;
}
//Write the image bits for each image
for(i=0;i <lpIR-> nNumImages;i++)
{
DWORD dwTemp=lpIR-> IconImages[i].lpbi-> bmiHeader.biSizeImage;
//Set the sizeimage member to zero
lpIR-> IconImages[i].lpbi-> bmiHeader.biSizeImage=0;
//Write the image bits to file
if(!WriteFile(hFile,lpIR-> IconImages[i].lpBits,lpIR-> IconImages[i].dwNumBytes,&dwBytesWritten,NULL))
return FALSE;
if(dwBytesWritten!=lpIR-> IconImages[i].dwNumBytes)
return FALSE;
//set it back
lpIR-> IconImages[i].lpbi-> bmiHeader.biSizeImage=dwTemp;
}
CloseHandle(hFile);
return FALSE;
}