将位图转换为图标

Muh*_*dar 18 .net c# 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);
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多来弄清楚问题,但不能.请告诉我问题出在哪里.

Nig*_*ist 10

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

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

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

  • 难道没有一种便携的方法可以做到这一点吗? (2认同)

Den*_*nis 8

本文介绍如何将位图转换为图标.

http://www.go4expert.com/forums/showthread.php?t=19250

它看起来非常类似于你的:

using (Cbitmap = new Bitmap(sourceImage.Text))
{
    Cbitmap.MakeTransparent(Color.White);
    System.IntPtr icH = Cbitmap.GetHicon();
    Icon ico = Icon.FromHandle(icH);
}
using (System.IO.FileStream f = new System.IO.FileStream(destinationFldr.Text + "\\image.ico", System.IO.FileMode.OpenOrCreate))
{
    ico.Save(f);
}
Run Code Online (Sandbox Code Playgroud)

试试看.

编辑:添加了使用声明.


Muh*_*dar 6

此代码的唯一问题是它支持高达 128x128 的位图图像。

如果位图的大小更大,它会产生一个空白的 ico 文件。