zoukankan      html  css  js  c++  java
  • C# Icon转Byte , Byte转Icon

    Icon直接保存成ico文件会严重失真,可以保存为png格式。

    但如果要转换到byte,直接使用Icon.ToBitmap().Save方法会出错,需要带一点参数。具体代码如下

        public class IconHelper
        {
            /// <summary>
            /// Byte转Icon
            /// </summary>
            /// <param name="buffer"></param>
            /// <returns></returns>
            public static Icon FromByte(byte[] buffer)
            {
                return Icon.FromHandle(new System.Drawing.Bitmap(new MemoryStream(buffer)).GetHicon());
            }
    
            /// <summary>
            /// Icon转Byte
            /// </summary>
            /// <param name="icon"></param>
            /// <returns></returns>
            public static byte[] ToByte(Icon icon)
            {
                Encoder myEncoder = Encoder.Quality;
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100);
                EncoderParameters encoders = new EncoderParameters(1);
                encoders.Param[0] = myEncoderParameter;
                ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/png");
    
                using (MemoryStream ms = new MemoryStream())
                {
                    icon.ToBitmap().Save(ms, myImageCodecInfo, encoders);
                    return ms.GetBuffer();
                }
            }
    
            private static ImageCodecInfo GetEncoderInfo(string mimeType)
            {
                int j;
                ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
                for (j = 0; j < encoders.Length; ++j)
                {
                    if (encoders[j].MimeType == mimeType)
                        return encoders[j];
                }
                return null;
            }
        }
  • 相关阅读:
    Activator.CreateInstance 反射实例化对象
    MVC Form提交
    Redis 下载
    List<T> 序列化与反序列化
    快速反射DataTable
    数据库特性
    javascript判断文件大小
    MD5
    HttpHelper
    cacheHelper
  • 原文地址:https://www.cnblogs.com/xyz0835/p/4850063.html
Copyright © 2011-2022 走看看