首页 > 代码库 > .net 根据图片网络地址获取图片二进制字节数据流

.net 根据图片网络地址获取图片二进制字节数据流

 

        /// <summary>
        ///根据html路径获取图片的字节
        /// </summary> 
        /// <param name="picSize">图片尺寸,原图:1,大图:2,中图:3,小图:4</param> 
        /// <param name="serverPath">图片服务器地址</param>
        /// <returns></returns>
        public static byte[] GetImageByteByHtmlImgUrl(string imgSize, string serverPath)
        {
            byte[] bt = new byte[4096];

            try
            {
                serverPath = serverPath.Replace("_1.", string.Format("_{0}.", imgSize));
                Image obj = Image.FromStream(System.Net.WebRequest.Create(serverPath).GetResponse().GetResponseStream());
                bt = ImageToByteArray(obj);  //使用ImageToByteArray()函数 将Image类型转成Byte[]类型
                obj.Dispose();
                return bt;
            }
            catch  //如果获取异常 则使用资源中的图片显示 
            {
                //Image obj = Image.FromStream("");
                //byte[] bt = ImageToByteArray(obj);
                //obj.Dispose();
                //return bt;
            }

            return bt;
        }

        /// <summary>
        /// 根据image获取图片的字节
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        private static byte[] ImageToByteArray(Image image)
        {
            System.IO.MemoryStream mStream = new System.IO.MemoryStream();
            image.Save(mStream, System.Drawing.Imaging.ImageFormat.Png);
            byte[] ret = mStream.ToArray();
            mStream.Close();
            return ret;
        }

CodeBy:博客园-曹永思,http://www.cnblogs.com/yonsy/p/3716483.html
根据图片二进制字节数据流获取图片Image实例

  /// <summary>
        /// 根据图片字节流获取Image实例
        /// </summary>
        /// <param name="imagebyte"></param>
        /// <returns></returns>
        public static Image SetByteToImage(byte[] imagebyte)
        {
            Image image;
            MemoryStream imagememorystream = new MemoryStream(imagebyte, 0, imagebyte.Length);
            image = Image.FromStream(imagememorystream);
            return image;
        }