如何将Bitmap保存为图标?

时间:2010-10-28 11:38:18

标签: c# .net vb.net icons bitmap

我需要保存从图像文件(.png,.jpeg,.bmp)加载的Bitmap对象,并将其另存为图标(.ico)到单独的文件中。

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

using System.Drawing;

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

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

下一步是从Bitmap获取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中实现吗?

提前致谢。

1 个答案:

答案 0 :(得分:-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);
        }
    }
}