我正在尝试将位图转换为图标.但是有一些错误,因为结果文件只是空白.
private void btnCnvrtSave_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(sourceFile); //sourceFile = openfiledialog.FileName;
IntPtr Hicon = bmp.GetHicon();
Icon myIcon = Icon.FromHandle(Hicon);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Save Icon";
sfd.Filter = "Icon|*.ico";
sfd.ShowDialog();
FileStream fileStream = new FileStream(sfd.FileName, FileMode.OpenOrCreate);
myIcon.Save(fileStream);
fileStream.Flush();
fileStream.Close();
MessageBox.Show("Image is converted successfully!");
//Process.Start(sfd.FileName);
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了很多来弄清楚问题,但不能.请告诉我问题出在哪里.
我使用Win32 SHGetFileInfo来获取属于某个文件的图标的句柄.有很多描述如何执行此操作,也可以在stackoverflow上执行此操作,例如:获取shell使用的图标
调用该函数后,您将拥有一个带有Icon图标句柄的结构.使用静态方法Icon.FromHandle我可以将它转换为System.Drawing.Icon类的对象.该类实现System.IDisposable.正确的用法如下:
using (Icon icon = Icon.FromHandle(shFileInfo.hIcon))
{
// do what you need to do with the icon
}
Run Code Online (Sandbox Code Playgroud)
在离开using语句时,处理图标对象.
MSDN在Icon.FromHandle的描述中警告(点击查看):
使用此方法时,必须使用Win32 API中的DestroyIcon方法处置原始图标,以确保释放资源.
释放此Icon使用的所有资源.
题:
Dispose()对象是否足够,或者我应该调用Dispose()和DestroyIcon,还是调用DestroyIcon而不是Disposing对象?