1.ICON轉Image
Icon icon = Icon.ExtractAssociatedIcon(@"D:\XXXX\VSLogo.ico"); MemoryStream mStream = new MemoryStream(); icon.Save(mStream); Image image = Image.FromStream(mStream);
2.Image轉ICON
1 /// <summary> 2 /// 轉換Image為Icon 3 /// </summary> 4 /// <param name="image">要轉換為圖標的Image對象</param> 5 /// <param name="nullTonull">當image為null時是否返回null。false則拋空引用異常</param> 6 /// <exception cref="ArgumentNullException" /> 7 /// <returns></returns> 8 public static Icon ConvertToIcon(Image image, bool nullTonull = false) 9 { 10 if (image == null) 11 { 12 if (nullTonull) 13 { 14 return null; 15 } 16 throw new ArgumentNullException("Image is null"); 17 } 18 19 using (MemoryStream msImg = new MemoryStream(), msIco = new MemoryStream()) 20 { 21 image.Save(msImg, ImageFormat.Png); 22 23 using (var bin = new BinaryWriter(msIco)) 24 { 25 //寫圖標頭部 26 bin.Write((short)0); //0-1保留 27 bin.Write((short)1); //2-3文件類型。1=圖標, 2=光標 28 bin.Write((short)1); //4-5圖像數量(圖標可以包含多個圖像) 29 30 bin.Write((byte)image.Width); //6圖標寬度 31 bin.Write((byte)image.Height); //7圖標高度 32 bin.Write((byte)0); //8顏色數(若像素位深>=8,填0。這是顯然的,達到8bpp的顏色數最少是256,byte不夠表示) 33 bin.Write((byte)0); //9保留。必須為0 34 bin.Write((short)0); //10-11調色板 35 bin.Write((short)32); //12-13位深 36 bin.Write((int)msImg.Length); //14-17位圖數據大小 37 bin.Write(22); //18-21位圖數據起始字節 38 39 //寫圖像數據 40 bin.Write(msImg.ToArray()); 41 42 bin.Flush(); 43 bin.Seek(0, SeekOrigin.Begin); 44 return new Icon(msIco); 45 } 46 } 47 }