/// <summary>
/// 轉換Image為Icon
/// </summary>
/// <param name="image">要轉換為圖標的Image對象</param>
/// <param name="nullTonull">當image為null時是否返回null。false則拋空引用異常</param>
/// <exception cref="ArgumentNullException" />
public static Icon ConvertToIcon(Image image, bool nullTonull = false)
{
if (image == null)
{
if (nullTonull) { return null; }
throw new ArgumentNullException("image");
}
using (MemoryStream msImg = new MemoryStream()
, msIco = new MemoryStream())
{
image.Save(msImg, ImageFormat.Png);
using (var bin = new BinaryWriter(msIco))
{
//寫圖標頭部
bin.Write((short)0); //0-1保留
bin.Write((short)1); //2-3文件類型。1=圖標, 2=光標
bin.Write((short)1); //4-5圖像數量(圖標可以包含多個圖像)
bin.Write((byte)image.Width); //6圖標寬度
bin.Write((byte)image.Height); //7圖標高度
bin.Write((byte)0); //8顏色數(若像素位深>=8,填0。這是顯然的,達到8bpp的顏色數最少是256,byte不夠表示)
bin.Write((byte)0); //9保留。必須為0
bin.Write((short)0); //10-11調色板
bin.Write((short)32); //12-13位深
bin.Write((int)msImg.Length); //14-17位圖數據大小
bin.Write(22); //18-21位圖數據起始字節
//寫圖像數據
bin.Write(msImg.ToArray());
bin.Flush();
bin.Seek(0, SeekOrigin.Begin);
return new Icon(msIco);
}
}
}