c# - 将位图转换为图标

标签 c# .net winforms

我正在尝试将位图转换为图标。但是有一些错误,因为生成的文件只是空白。

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);
}

我已经尝试了很多方法来找出问题所在,但没能成功。 请告诉我问题出在哪里。

最佳答案

请在GetHicon 之后使用DestroyIcon,以防止内存泄漏

[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

MSDN:https://msdn.microsoft.com/en-us/library/system.drawing.bitmap.gethicon%28v=vs.110%29.aspx

关于c# - 将位图转换为图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8174393/

相关文章:

c# - 不同 usercontrol.ascx 中的两个验证按钮

c# - .Net中如何播放 "New Mail"系统音?

c# - 在没有 Try Catch 的情况下检查文件锁定

c# - GitSharp 与 NGit

c# - 确定 DataGridView 中除新行之外的行数

c# - 按钮单击打开 richTextBox 并显示读取文件

c# - 如何编写自动缩放到系统字体和 dpi 设置的 WinForms 代码?

c# - RavenDB 获取查询不起作用的总计数

c# - 在构建后事件期间确定程序集版本

面向初学者的 C# GUI 编程 : Where to start?