Как программно сохранить изображение из URL? Я использую С# и должен иметь возможность захватывать изображения с URL-адреса и хранить их локально.... и нет, я не краду:)
Как программно сохранить изображение с URL-адреса?
Ответ 1
Было бы проще написать что-то вроде этого:
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);
Ответ 2
Вам просто нужно сделать базовый HTTP-запрос, используя HttpWebRequest для URI изображения, затем возьмите полученный поток байтов, затем сохраните этот поток в файл.
Вот пример того, как это сделать...
'В качестве побочного примечания, если изображение очень велико, вы можете разбить 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();
}
}
}
}
Ответ 3
Пример в aspx (С#)
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 С# Загрузка или сохранение файла изображения по URL