转】 C# 图片格式(JPG,BMP,PNG,GIF)等转换为ICO图标

using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace ICOTest
{
    public partial class Form1 : Form
    {
        string FileName = "C:\\";
        public Form1()
        {
            InitializeComponent();
        }

        //核心代码
        private void button1_Click(object sender, EventArgs e)
        {
            Size size = new Size(32, 32);
            //获得原始图片文件
            using (Bitmap bm = new Bitmap(FileName))
            {
                //从现有图像缩小,为了得到合适的ICO文件
                using (Bitmap iconBm = new Bitmap(bm, size))
                {
                    //如果是windows调用,直接下面一行代码就可以了
                    //此代码不能在web程序中调用,会有安全异常抛出
                    using (Icon icon = Icon.FromHandle(iconBm.GetHicon()))
                    {
                        string Name_ = "C:\\ICO\\" + DateTime.Now.Ticks.ToString() + ".ico";
                        using (Stream stream = new System.IO.FileStream(Name_, System.IO.FileMode.Create))
                        {

                            icon.Save(stream);
                            MessageBox.Show("转换成功。路径是:" + Name_);
                        }
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "JPG|*.jpg|BMP|*.bmp|PNG|*.png|GIF|*.gif";
            DialogResult D = openFileDialog1.ShowDialog();
            if (D == DialogResult.OK)
            {
                FileName = this.openFileDialog1.FileName.Trim();
                this.textBox1.Text = FileName;
            }
        }
    }
}

图像界面效果如下:

posted @ 2010-11-26 16:01  L_tommy  阅读(4741)  评论(1编辑  收藏  举报