当前位置:
首页 >
C# ICON和Image互转
发布时间:2023/12/13
47
生活家
生活随笔
收集整理的这篇文章主要介绍了
C# ICON和Image互转
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1.ICON转Image
Icon icon = Icon.ExtractAssociatedIcon(@"D:XXXXVSLogo.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 }
本文来自博客园,作者:ganjiqi,转载请注明原文链接:https://www.cnblogs.com/ganjiqi/p/13300059.html
总结
以上是生活随笔为你收集整理的C# ICON和Image互转的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: php iis ajax 无效,IIS7
- 下一篇: Apache Atlas部署安装