C# 圖片格式(JPG,BMP,PNG,GIF)等轉換爲ICO圖標
2010-06-01 12:43 P.M.
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; } } } }
圖像界面效果如下:
|