6

我只想从 Internet 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;
    }
4

4 回答 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);
            }
        }
    }
}
于 2010-09-07T14:37:36.857 回答
2

为什么不使用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);
于 2012-11-07T16:56:11.113 回答
0

这是我用来从 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 );
       }
    }
于 2010-09-07T14:40:30.553 回答
-3

最简单的是

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

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

于 2013-05-05T18:55:43.010 回答