如何将位图保存为图标?

7

我需要将从图像文件(.png, .jpeg, .bmp)加载的位图对象保存为图标(.ico)到另一个文件中。

首先,我尝试使用Icon ImageFormat将位图对象保存到文件中:

using System.Drawing;

Bitmap bmp = (Bitmap)pictureBox1.Image;
bmp.Save(@"C:\icon.ico", Imaging.ImageFormat.Icon);

这个失败了,因为生成的图标格式不正确,不能用作图标。

下一个是从位图获取HIcon并将其保存到文件中:

using System.Drawing;
using System.IO;

StreamWriter iconWriter = new StreamWriter(@"C:\icon.ico");
Icon ico = Icon.FromHandle(((Bitmap)pictureBox1.Image).GetHicon())
ico.Save(iconWriter.BaseStream);
iconWriter.Close();
iconWriter.Dispose();

这个也不能胜任。尽管图标文件写得很好,它只有16种颜色以及有限的宽度和高度。

我希望能够编写具有自定义宽度和高度的图标,并保留原始图像的颜色。这在.NET中可行吗?

提前致谢。


2
GetHicon()的效果确实很差。试试这个:http://www.codeproject.com/KB/cs/IconLib.aspx - Hans Passant
1
我也成功地使用了这个:http://www.codeproject.com/KB/GDI-plus/safeicon.aspx - Chris Rae
1个回答

1
一个使用命名空间 System.IO 的工作示例可以是这样的:
[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static bool DestroyIcon(IntPtr handle);

private void buttonConvert2Ico_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog 

    openFileDialog1.InitialDirectory = "C:\\Data\\";
    openFileDialog1.Filter = "BitMap(*.bmp)|*.bmp";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.RestoreDirectory = true;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            string sFn = openFileDialog1.FileName;
            MessageBox.Show("Filename=" + sFn);
            string destFileName = sFn.Substring(0, sFn.Length -3) +"ico";

            // Create a Bitmap object from an image file.
            Bitmap bmp = new Bitmap(sFn);

            // Get an Hicon for myBitmap. 
            IntPtr Hicon = bmp.GetHicon();

            // Create a new icon from the handle. 
            Icon newIcon = Icon.FromHandle(Hicon);

            //Write Icon to File Stream
            System.IO.FileStream fs = new System.IO.FileStream(destFileName, System.IO.FileMode.OpenOrCreate);
            newIcon.Save(fs);
            fs.Close();
            DestroyIcon(Hicon);

            //DestroyIcon( hIcon);
            setStatus("Created icon From=" + sFn + ", into " + destFileName);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read/write file. Original error: " + ex.Message);
        }
    }
}

1
Chris,这只是我问题中第二个示例的复制。 - Nikola Malešević

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接