首页 > Windows开发 > 详细

C# Icon转Byte , Byte转Icon

时间:2015-09-30 19:28:45      阅读:337      评论:0      收藏:0      [点我收藏+]

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

 

C# Icon转Byte , Byte转Icon

原文:http://www.cnblogs.com/xyz0835/p/4850063.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!