上一步,我们已经获取了图片应该保存的地址。现在只需要传入URL把图片下载到指定目录。
从网上下载图片也有俩种方法。
第一种:
WebRequest request = WebRequest.Create("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1578031102838&di=1d5e032e5139eef33ab821b5f3522b64&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017ee65835168ca801219c779ff093.jpg"); WebResponse response = request.GetResponse(); Stream reader = response.GetResponseStream(); FileStream writer = new FileStream($"{System.Environment.CurrentDirectory}/test.jpg", FileMode.Create, FileAccess.ReadWrite);//获取根目录方法二 byte[] buff = new byte[512]; int c = 0; //实际读取的字节数 while ((c = reader.Read(buff, 0, buff.Length)) > 0) { writer.Write(buff, 0, c); } writer.Close(); writer.Dispose(); reader.Close(); reader.Dispose(); response.Close();
第二种:
//下载图片的方法二 using (WebClient webClient = new WebClient()) { webClient.DownloadFile("http://服务器地址/1.png", @"d:\temp\image1.png"); }