IconTool.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Drawing;
  8. using System.Drawing.Imaging;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace Azylee.Core.IOUtils.ImageUtils
  14. {
  15. public class IconTool
  16. {
  17. /// <summary>
  18. /// 将 Image 保存到指定目录文件名的 Icon
  19. /// </summary>
  20. /// <param name="image"></param>
  21. /// <param name="file"></param>
  22. /// <returns></returns>
  23. public static bool Save(Image image, string file)
  24. {
  25. if (image != null)
  26. {
  27. using (Icon icon = ConvertToIcon(image))
  28. {
  29. try
  30. {
  31. FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
  32. icon.Save(fs);
  33. fs.Flush();
  34. fs.Close();
  35. fs.Dispose();
  36. return true;
  37. }
  38. catch { }
  39. }
  40. }
  41. return false;
  42. }
  43. /// <summary>
  44. /// 转换Image为Icon
  45. /// </summary>
  46. /// <param name="image">要转换为图标的Image对象</param>
  47. /// <param name="nullTonull">当image为null时是否返回null。false则抛空引用异常</param>
  48. /// <exception cref="ArgumentNullException" />
  49. public static Icon ConvertToIcon(Image image, bool nullTonull = false)
  50. {
  51. if (image == null)
  52. {
  53. if (nullTonull) { return null; }
  54. throw new ArgumentNullException("image");
  55. }
  56. using (MemoryStream msImg = new MemoryStream()
  57. , msIco = new MemoryStream())
  58. {
  59. image.Save(msImg, ImageFormat.Png);
  60. using (var bin = new BinaryWriter(msIco))
  61. {
  62. //写图标头部
  63. bin.Write((short)0); //0-1保留
  64. bin.Write((short)1); //2-3文件类型。1=图标, 2=光标
  65. bin.Write((short)1); //4-5图像数量(图标可以包含多个图像)
  66. bin.Write((byte)image.Width); //6图标宽度
  67. bin.Write((byte)image.Height); //7图标高度
  68. bin.Write((byte)0); //8颜色数(若像素位深>=8,填0。这是显然的,达到8bpp的颜色数最少是256,byte不够表示)
  69. bin.Write((byte)0); //9保留。必须为0
  70. bin.Write((short)0); //10-11调色板
  71. bin.Write((short)32); //12-13位深
  72. bin.Write((int)msImg.Length); //14-17位图数据大小
  73. bin.Write(22); //18-21位图数据起始字节
  74. //写图像数据
  75. bin.Write(msImg.ToArray());
  76. bin.Flush();
  77. bin.Seek(0, SeekOrigin.Begin);
  78. return new Icon(msIco);
  79. }
  80. }
  81. }
  82. }
  83. }