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;
        }
    }

 

posted @ 2015-09-30 18:36  逍遥子k  阅读(1107)  评论(0编辑  收藏  举报