在wpf中下载时显示图像

时间:2012-05-18 11:25:06

标签: c# wpf image download

我使用以下代码下载图片。

    byte[] buffer = new byte[1024];

    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
    httpRequest.Timeout = 30000;
    httpRequest.Method = "GET";
    httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0";
    httpRequest.Accept = "image/png,image/*;q=0.8,*/*;q=0.5";

    using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
    {
        using (Stream responseStream = httpResponse.GetResponseStream())
        {
            MemoryStream memStream = new MemoryStream();
            int bytesRead;
            while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }
            memStream.Seek(0, SeekOrigin.Begin);
            return memStream;
        }
    }

下载后,在WPF图像控件中显示它。

    BitmapImage bmpImage = new BitmapImage();
    bmpImage.BeginInit();
    bmpImage.StreamSource = memStream;
    bmpImage.CacheOption = BitmapCacheOption.OnLoad;
    bmpImage.EndInit();

    backIMG.Source = bmpImage;

我想在下载时显示图像(在浏览器中加载类似图像) 我怎么能这样做?

(对不起英语不好)

0 个答案:

没有答案