摘要:C# 將指定的圖檔轉換成表單的Icon顯示。
這邊介紹如何將指定的圖檔轉換成.ico格式
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace Test_ImageTransformeIcon
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_OpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog oOpenFileDialog = new OpenFileDialog())
{
oOpenFileDialog.Filter = "(JPEG)jpg|*.jpg;*.jpeg|(BMP).bmp|*.bmp";
if (oOpenFileDialog.ShowDialog() == DialogResult.OK)
{
if (File.Exists(oOpenFileDialog.FileName))
{
txtPath.Text = oOpenFileDialog.FileName;
btnPaste.Enabled = true;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.txtPath.ReadOnly = true;
this.btnPaste.Enabled = false;
this.btnConvert.Enabled = false;
}
private void btnPaste_Click(object sender, EventArgs e)
{
try
{
using (FileStream fs = File.OpenRead(txtPath.Text))
{
// 將圖形檔的資料讀入一個 Byte 陣列中。
Byte[] myBinaryData = new Byte[(int)(fs.Length)];//先設定位元組陣列的長度
fs.Read(myBinaryData, 0, (int)(fs.Length));
// 根據 Byte 陣列來建立一個 MemoryStream 物件。
MemoryStream buffer = new MemoryStream(myBinaryData);
// 將 MemoryStream 物件的目前位置移至開頭處。
buffer.Position = 0;
// 將圖形檔的二進位資料讀入一個 Image 物件中。
picbox.BackgroundImage = Image.FromStream(buffer);
picbox.BackgroundImageLayout = ImageLayout.Center;
btnConvert.Enabled = true;
}
}
catch
{
btnConvert.Enabled = false;
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
using (MemoryStream memoryStream = new MemoryStream())
{
//指定要轉換的圖檔給 Image 物件。
Image oImage = picbox.BackgroundImage;
//利用 MemoryStream 物件將 Image 儲存成指定的型式。
oImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
//再轉給 Icon 物件。
Icon myIcon = Icon.FromHandle(new Bitmap(memoryStream).GetHicon());
this.Icon = myIcon;//設定表單Icon
memoryStream.Close();
memoryStream.Dispose();
}
}
} } |
<<後記>>
1.後來發現有更簡單的方法設定表單的 icon
//設定檔案路徑
string sPath = System.IO.Path.Combine(Application.StartupPath, @"Images\favicon.ico");
//判斷檔案是否存在
if (File.Exists(sPath)) {
//取得 Icon 物件
Icon myIcon = Icon.FromHandle(new Bitmap(Image.FromFile(sPath)).GetHicon());
if (myIcon != null) {
//設定表單 Icon
this.Icon = myIcon;
}
}
<<後記2>>
透過朋友告知,使用 <<後記1>> 的作法,直接讀取 ico 圖檔,會出現圖片失真的情形,
所以修正 code 。
if (string.IsNullOrEmpty(FilePath)) { throw new ArgumentNullException(); }
Icon myIcon = null;
if (File.Exists(FilePath)) {
try {
//取得 Icon 物件
using(Icon oIcon = new Icon(FilePath)){
//建立副本
myIcon = (Icon)oIcon.Clone();
}
}
catch (Exception ex) {
AppFunc.HandleException2(ex, "遺失圖檔!");
}
}
三小俠 小弟獻醜,歡迎指教