C#抓取网络图片保存到本地

企鹅不笨 分享于 1分钟前 28618阅 0人收藏此代码, 我要收藏

这段代码可以抓取指定的url的网络图片,并保存到本地

C#
        public Bitmap Get_img()
        {
            Bitmap img = null;
            HttpWebRequest req;
            HttpWebResponse res = null;
                try
                {
                    System.Uri httpUrl = new System.Uri("http://xxx.com/xxx.png ");
                    req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                    req.Timeout = 180000; //设置超时值10秒
                       req.UserAgent = "XXXXX";
                    req.Accept = "XXXXXX";
                    req.Method = "GET";
                    res = (HttpWebResponse)(req.GetResponse());      
                       img = new Bitmap(res.GetResponseStream());//获取图片流                 
                    img.Save(@"E:/" + DateTime.Now.ToFileTime().ToString() + ".png");//随机名
                }

                catch (Exception ex)
                {
                     string aa= ex.Message;
                }
                finally
                {
                    res.Close();
                }
                     return img;
        }
//该代码片段来自于: http://www.sharejs.com/codes/csharp/2122

标签:
  • 抓取图片
  • 抓取网页
  • 文件抓取