从URL同步下载图像

问题描述 投票:6回答:4

我只是想从一个互联网URL获取一个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;
    }
wpf url download bitmapimage
4个回答
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
投票

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

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
投票

最简单的是

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

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

© www.soinside.com 2019 - 2024. All rights reserved.