从URL同步下载图像

时间:2010-09-07 14:27:48

标签: wpf url download bitmapimage

我只想从互联网网址获取BitmapImage,但我的功能似乎无法正常工作,它只返回了我的一小部分图片。我知道WebResponse正在异步工作,这就是我遇到这个问题的原因,但我怎么能同步呢?

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

4 个答案:

答案 0 :(得分:10)

首先,您应该只下载图像,并将其本地存储在临时文件或MemoryStream中。然后从中创建BitmapImage对象。

您可以下载图片,例如:

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

答案 1 :(得分:1)

为什么不使用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);

答案 2 :(得分:0)

这是我用来从网址抓取图片的代码....

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

答案 3 :(得分:-3)

最简单的是

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

然后您可以更改BitmapCacheOption以启动检索过程。但是,图像是在异步中检索的。但你不应该太在意