Synchronously download an image from URL
First you should just download the image, and store it locally in a temporary file or in a MemoryStream
. And then create the BitmapImage
object from it.
You can download the image for example like this:
Uri urlUri = new Uri(url);
var request = WebRequest.CreateDefault(urlUri);
byte[] buffer = new byte[4096];
using (var target = new FileStream(targetFileName, FileMode.Create, FileAccess.Write))
{
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
target.Write(buffer, 0, read);
}
}
}
}
Why not use System.Net.WebClient.DownloadFile
?
string url = @"http://www.google.ru/images/srpr/logo3w.png";
string file = System.IO.Path.GetFileName(url);
System.Net.WebClient cln = new System.Net.WebClient();
cln.DownloadFile(url,file);