【问题标题】:How to save Bitmap as icon? [duplicate]如何将位图保存为图标? [复制]
【发布时间】:2011-05-01 20:18:17
【问题描述】:

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

首先我尝试将 Bitmap 对象保存到具有 Icon ImageFormat 的文件中:

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 中实现吗?

提前致谢。

【问题讨论】:

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


【解决方案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);
        }
    }
}

【讨论】:

  • 克里斯,这只是我问题中第二个示例的复制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 2018-01-22
相关资源
最近更新 更多