Image扩展,如何将网络图片显示在自己的程序中

因为图片来源多种多样,默认框架已经提供了好几种图片读取方式,比如Image.FromFile,Image.FromHbitmap,Image.FromStream,但就是没有提供Image.FromNet,所以这里写了个通用的扩展方法,可以支持从Net环境中读取图片(Http、Ftp等),因为只是个扩展,也没啥好说的,直接上代码就是

    using System.Drawing;
    using System.Net;
    public static class ImageExtensions
    {
        /// <summary>
        /// 通过NET获取网络图片
        /// </summary>
        /// <param name="url">要访问的图片所在网址</param>
        /// <param name="requestAction">对于WebRequest需要进行的一些处理,比如代理、密码之类</param>
        /// <param name="responseFunc">如何从WebResponse中获取到图片</param>
        /// <returns></returns>
        public static Image GetImageFromNet(this string url, Action<WebRequest> requestAction = null, Func<WebResponse, Image> responseFunc = null)
        {
            return new Uri(url).GetImageFromNet(requestAction, responseFunc);
        }
        /// <summary>
        /// 通过NET获取网络图片
        /// </summary>
        /// <param name="url">要访问的图片所在网址</param>
        /// <param name="requestAction">对于WebRequest需要进行的一些处理,比如代理、密码之类</param>
        /// <param name="responseFunc">如何从WebResponse中获取到图片</param>
        /// <returns></returns>
        public static Image GetImageFromNet(this Uri url, Action<WebRequest> requestAction = null, Func<WebResponse, Image> responseFunc = null)
        {
            Image img;
            try
            {
                WebRequest request = WebRequest.Create(url);
                if (requestAction != null)
                {
                    requestAction(request);
                }
                using (WebResponse response = request.GetResponse())
                {
                    if (responseFunc != null)
                    {
                        img = responseFunc(response);
                    }
                    else
                    {
                        img = Image.FromStream(response.GetResponseStream());
                    }
                }
            }
            catch
            {
                img = null;
            }
            return img;
        }
    }
调用方法就是

            var uri = "http://t1.mmonly.cc/uploads/allimg/tuku2/16343123c-11.jpg";
            //var uri = new Uri("http://t1.mmonly.cc/uploads/allimg/tuku2/16343123c-11.jpg");
            var img = uri.GetImageFromNet(
            //(request) =>
            //{//此处可以对request进行相关设定,因为此部分均为基类,所以也可以用于FtpWebRequest之类
            //    request.Timeout = 2000;
            //},
            //(response) =>
            //{//此处可以确定如何从response中获取图片,同时可以包括相关判断之类
            //    return Image.FromStream(response.GetResponseStream());
            //}
            );




你可能感兴趣的:(网络,图片,扩展)