【问题标题】:Synchronously download an image from URL从 URL 同步下载图像
【发布时间】:2010-09-07 14:27:47
【问题描述】:

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

【问题讨论】:

    标签: wpf url download bitmapimage


    【解决方案1】:

    首先,您应该只下载图像,并将其存储在本地临时文件或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);
                }
            }
        }
    }
    

    【讨论】:

    • 运气不太好,我的图片还是部分下载到了MemoryStream中,或许你可以给我一个示例代码?
    • 从响应流中读取时,它不会填满缓冲区,就像从本地文件中读取时一样。所以读取的字节数会少于缓冲区的大小。但是它将大于 0,这表明尚未到达文件末尾。我想这是无法完全从url读取图片失败的关键。
    • 好的,这个样例可以下载图片,我现在应该可以将该文件转换为 BitmapImage。
    【解决方案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);
    

    【讨论】:

      【解决方案3】:

      这是我用来从 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 );
             }
          }
      

      【讨论】:

        【解决方案4】:

        最简单的是

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-24
          • 1970-01-01
          • 2017-06-12
          • 2015-10-01
          • 2021-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多