Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronously download an image from URL

I just want to get a BitmapImage from a internet URL, but my function doesn't seem to work properly, it only return me a small part of the image. I know WebResponse is working async and that's certainly why I have this problem, but how can I do it synchronously?

    internal static BitmapImage GetImageFromUrl(string url)
    {
        Uri urlUri = new Uri(url);
        WebRequest webRequest = WebRequest.CreateDefault(urlUri);
        webRequest.ContentType = "image/jpeg";
        WebResponse webResponse = webRequest.GetResponse();

        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.StreamSource = webResponse.GetResponseStream();
        image.EndInit();

        return image;
    }
like image 753
Karnalta Avatar asked Sep 07 '10 14:09

Karnalta


2 Answers

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);
            }
        }
    }
}
like image 149
treaschf Avatar answered Nov 05 '22 18:11

treaschf


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);
like image 2
mdn Avatar answered Nov 05 '22 18:11

mdn