MFC将图片转换成ico文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MFC将图片转换成ico文件相关的知识,希望对你有一定的参考价值。

#include "atlimage.h"
HICON ToIcon(int cx,int cy)
{
	CImage img;
	img.Load("cap.bmp");//可以是jpg,png,gif格式图片
	int w = img.GetWidth();
	int h = img.GetHeight();

	CDC * dc = CDC::FromHandle(GetWindowDC(GetDesktopWindow()));
	CDC mdc;
	mdc.CreateCompatibleDC(dc);
	CBitmap bmp;
	bmp.CreateCompatibleBitmap(dc,cx,cy);
	HBITMAP hOldBmp = (HBITMAP)mdc.SelectObject(bmp);
	img.StretchBlt(mdc.m_hDC,0,0,cx,cy,0,0,w,h,SRCCOPY);

	HBITMAP hBmp = (HBITMAP)bmp.m_hObject;

	ICONINFO iconinfo;
	memset(&iconinfo,0,sizeof(iconinfo));
	iconinfo.fIcon = 1;
	iconinfo.hbmColor = hBmp;
	iconinfo.hbmMask = hBmp;
	iconinfo.xHotspot = 0;
	iconinfo.yHotspot = 0;

	HICON hIcon = CreateIconIndirect(&iconinfo);//获取HICON
	/*if(hIcon)
	{
		dc->DrawIcon(0,0,hIcon);
	}*/
	img.Detach();

	PICTDESC pictdesc;
	memset(&pictdesc,0,sizeof(pictdesc));
	pictdesc.cbSizeofstruct = sizeof(pictdesc);
	pictdesc.picType = PICTYPE_ICON;
	pictdesc.icon.hicon = hIcon;

	IPicture * pPic = NULL;
	int ret = OleCreatePictureIndirect(&pictdesc,IID_IPicture,1,(LPVOID*)&pPic);
	
	LPSTREAM pStream = 0;
	CreateStreamOnHGlobal(0,TRUE,&pStream);

	LONG size = 0;
	pPic->SaveAsFile(pStream,TRUE,&size);

	//这步非常重要
	///////////////////////////////////////////////
	LARGE_INTEGER li;  
	li.HighPart =0;  
	li.LowPart =0;  
	ULARGE_INTEGER ulnewpos;  
	pStream->Seek( li,STREAM_SEEK_SET,&ulnewpos);
	///////////////////////////////////////////////

	HANDLE hFile = CreateFile("1.ico",GENERIC_ALL,0,0,CREATE_ALWAYS,0,0);//生成ico文件
	if(hFile)
	{
		char * buf = new char[size];
		memset(buf,0,size);
		ULONG nRead = 0;
		pStream->Read(buf,size,&nRead);
		ULONG nWrited = 0;
		WriteFile(hFile,buf,nRead,&nWrited,0);
		CloseHandle(hFile);
	}
	return hIcon;
}

  

以上是关于MFC将图片转换成ico文件的主要内容,如果未能解决你的问题,请参考以下文章

ico图标的引用

如何把rar文件的图标保存成.ico文件?

如何将网页的title前面的图标替换成自己的图标

免费开源Blazor在线Ico转换工具

如何制作ICO文件?

如何制作ico图标