.net获取网络图片

using System.IO;
using System.Net;

namespace TestUpfile
{
    public class NetHelper
    {
        public static Stream GetImgStream(string url,string protocol="http")
        {
            WebResponse response = null;
            Stream stream = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                response = request.GetResponse();
                stream = response.GetResponseStream();
                if (response.ContentType.ToLower().StartsWith("text/")) return null;
                ////如果要转成byte
                //using (MemoryStream mstream = new MemoryStream())
                //{
                //    int count = 0;
                //    byte[] buffer = new byte[1024];
                //    int readnum = 0;
                //    while ((readnum = stream.Read(buffer, 0, 1024)) > 0)
                //    {
                //        count = count + readnum;
                //        mstream.Write(buffer, 0, 1024);
                //    }
                //    mstream.Position = 0;
                //    using (BinaryReader br = new BinaryReader(mstream))
                //    {
                //        byte[] bytes = br.ReadBytes(count);
                //    }
                //}
                return stream;
            }
            catch
            {

            }
            return stream;
        }

        /// <summary>
        /// 通过webClient获取图片的字节
        /// </summary>
        /// <param name="url">要下载的url</param>
        /// <param name="protocol"></param>
        /// <returns></returns>
        public static byte[] GetImgBytes(string url)
        {
            byte[] bytes = null;
            try
            {
                if (url.Substring(0,5).ToLower() == "https")
                {
                    // 解决WebClient不能通过https下载内容问题
                    System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                        delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                 System.Security.Cryptography.X509Certificates.X509Chain chain,
                                 System.Net.Security.SslPolicyErrors sslPolicyErrors)
                        {
                            return true; // **** Always accept
                        };
                }
                WebClient client = new WebClient();
                bytes=client.DownloadData(url);
                return bytes;
            }
            catch
            {
                return null;
            }
        }
    }
}

  

posted on 2019-11-13 17:54  ymworkroom  阅读(596)  评论(0编辑  收藏  举报