Frage

Ich möchte nur ein Bitmap von einer Internet-URL erhalten, aber meine Funktion zur Arbeit scheint nicht richtig, es nur zurückgeben mir einen kleinen Teil des Bildes. Ich weiß, WebResponse arbeitet async und das ist sicherlich, warum ich dieses Problem haben, aber wie kann ich es synchron?

    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;
    }
War es hilfreich?

Lösung

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);
            }
        }
    }
}

Andere Tipps

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);

this is the code i use to grab an image from a url....

   // get a stream of the image from the webclient
    using ( Stream stream = webClient.OpenRead( imgeUri ) ) 
    {
      // make a new bmp using the stream
       using ( Bitmap bitmap = new Bitmap( stream ) )
       {
          //flush and close the stream
          stream.Flush( );
          stream.Close( );
          // write the bmp out to disk
          bitmap.Save( saveto );
       }
    }

The simpliest is

Uri pictureUri = new Uri(pictureUrl);
BitmapImage image = new BitmapImage(pictureUri);

you can then change BitmapCacheOption to start the retrieval process. However, image is retrieved in async. But you shouldn't care much

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top