流与Image对象的转换

来源:互联网 发布:剑灵刘亦菲捏脸数据图 编辑:程序博客网 时间:2024/06/06 20:33
        /// <summary>        /// 将Image数据转换为byte数组        /// </summary>        /// <param name="pImage"></param>        /// <returns></returns>        public static byte[] ImageToObject(System.Drawing.Image pImage)        {            if (pImage == null)            {                return null;            }            //新建一个对象,避免内存冲突            System.Drawing.Bitmap bm = new System.Drawing.Bitmap(pImage);            System.IO.MemoryStream msImage = new System.IO.MemoryStream();            BinaryFormatter bfImage = new BinaryFormatter();            bfImage.Serialize(msImage, bm);            msImage.Close();            return msImage.ToArray();        }        /// <summary>        /// 将byte数组转换为Image对象        /// </summary>        /// <param name="byteArray"></param>        /// <returns></returns>        public static System.Drawing.Image ObjectToImage(byte[] byteArray)        {            if (byteArray == null)            {                return null;            }            System.IO.MemoryStream msImage = new System.IO.MemoryStream(byteArray, 0, byteArray.Length);            BinaryFormatter bfImage = new BinaryFormatter();            object objImage = null;            try            {                if (byteArray.Length > 3                  && ((byteArray[0] == 255                       && byteArray[1] == 216                       && byteArray[2] == 255                       && byteArray[3] == 224)                                   //判断是否为JPG                  || (                      byteArray[0] == 137                      && byteArray[1] == 80                      && byteArray[2] == 78                      && byteArray[3] == 71)                                     //判断是否为PNG                  || (                      byteArray[0] == 66                      && byteArray[1] == 77                      && byteArray[2] == 54                      && byteArray[3] == 83)                                    //BMP                  || (                      byteArray[0] == 71                      && byteArray[1] == 73                      && byteArray[2] == 70                      && byteArray[3] == 56)                                   //gif                 || (                      byteArray[0] == 66                      && byteArray[1] == 77                      && byteArray[2] == 40                      && byteArray[3] == 1)                      ))                {                    return System.Drawing.Image.FromStream(msImage);                }                                objImage = bfImage.Deserialize(msImage);            }            catch (Exception err)            {                string strErr = err.Message;            }            finally            {                msImage.Close();            }            return objImage as System.Drawing.Image;        }

    }