编程语言
首页 > 编程语言> > C# 保存网络图片至本地项目中

C# 保存网络图片至本地项目中

作者:互联网

1、获取项目根目录 System.AppDomain.CurrentDomain.BaseDirectory

以下为把图片转成流保存成文件

 1 #region 保存web图片到本地
 2         /// <summary>
 3         /// 保存web图片到本地
 4         /// </summary>
 5         /// <param name="imgUrl">web图片路径</param>
 6         /// <param name="path">保存路径</param>
 7         /// <param name="fileName">保存文件名</param>
 8         /// <returns></returns>
 9         public static string SaveImageFromWeb(string imgUrl, string path, string fileName)
10         {
11             if (path.Equals(""))
12                 throw new Exception("未指定保存文件的路径");
13             string imgName = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("/") + 1);
14             string defaultType = ".jpg";
15             string[] imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
16             string imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
17             string imgPath = "";
18             foreach (string it in imgTypes)
19             {
20                 if (imgType.ToLower().Equals(it))
21                     break;
22                 if (it.Equals(".bmp"))
23                     imgType = defaultType;
24             }
25 
26             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
27             request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Natas.Robot)";
28             request.Timeout = 3000;
29 
30             WebResponse response = request.GetResponse();
31             Stream stream = response.GetResponseStream();
32 
33             if (response.ContentType.ToLower().StartsWith("image/"))
34             {
35                 byte[] arrayByte = new byte[1024];
36                 int imgLong = (int)response.ContentLength;
37                 int l = 0;
38 
39                 if (fileName == "")
40                     fileName = imgName;
41 
42                 FileStream fso = new FileStream(path + fileName + imgType, FileMode.Create);
43                 while (l < imgLong)
44                 {
45                     int i = stream.Read(arrayByte, 0, 1024);
46                     fso.Write(arrayByte, 0, i);
47                     l += i;
48                 }
49 
50                 fso.Close();
51                 stream.Close();
52                 response.Close();
53                 imgPath = fileName + imgType;
54                 return imgPath;
55             }
56             else
57             {
58                 return "";
59             }
60         }
61         #endregion
View Code

注:以上代码适用于获取网络图片保存时会到参数无效时。

System.Drawing.Image.FromStream(ms) 这里会抛出异常,上网查阅资料说是透明度的问题不兼容,所以可以考虑直接用文件的形式保存下来,然后在获取对应的图片

标签:string,C#,保存,fileName,本地,imgType,response,imgUrl
来源: https://www.cnblogs.com/MycnBlogs7854/p/15034409.html