如何以编程方式从URL保存图像?我正在使用C#,需要能够从URL中获取图像并将其存储在本地。 ......不,我不偷东西:)
答案 0 :(得分:111)
写这样的东西会更容易:
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);
答案 1 :(得分:29)
您只需要使用 HttpWebRequest 为图像的URI创建一个基本的http请求,然后获取生成的字节流,然后将该流保存到文件中。
以下是如何执行此操作的示例...
'作为旁注,如果图像非常大,您可能需要将 br.ReadBytes(500000)分解为一个循环并一次抓取n个字节,然后编写每批字节检索它们。'
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ImageDownloader
{
class Program
{
static void Main(string[] args)
{
string imageUrl = @"http://www.somedomain.com/image.jpg";
string saveLocation = @"C:\someImage.jpg";
byte[] imageBytes;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream ))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
}
答案 2 :(得分:3)
aspx(c#)中的一个例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
public partial class download_file_from_url : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://4rapiddev.com/wp-includes/images/logo.jpg";
string file_name = Server.MapPath(".") + "\\logo.jpg";
save_file_from_url(file_name, url);
Response.Write("The file has been saved at: " + file_name);
}
public void save_file_from_url(string file_name, string url)
{
byte[] content;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes(500000);
br.Close();
}
response.Close();
FileStream fs = new FileStream(file_name, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(content);
}
finally
{
fs.Close();
bw.Close();
}
}
}
作者:HOAN HUYNH
ASP.Net C# Download Or Save Image File From URL
答案 3 :(得分:0)
我的解决方案是将图像预先保存到磁盘,然后再将美国保存为普通保存的图像:
remoteFile =“ http://xxx.yyy.com/image1.png”; localFile =“ c:\ myimage.png”;
WebClient webClient = new WebClient(); webClient.DownloadFile(remoteFile,localFile);