首页 新闻 会员 周边 捐助

关于WP7/WPF 异步加载图片的问题

0
悬赏园豆:50 [待解决问题]

问题如图。

最好是有高手在百忙之中给我写个DEMO!万分感谢!

这个问题困扰我好久了!新人

风行大地的主页 风行大地 | 初学一级 | 园豆:152
提问于:2013-04-28 23:59
< >
分享
所有回答(1)
1
Image img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};


ThreadStart thread = delegate
     {
     
         BitmapImage bmpImage = new BitmapImage();
         MemoryStream ms = new MemoryStream();

         FileStream fs = File.Open(@"C:\ImageFileName.jpg", FileMode.Open);
         MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);

         bmpImage.BeginInit();
         bmpImage.StreamSource = ms;
         bmpImage.EndInit();


         bmpImage.Freeze();

         Dispatcher.BeginInvoke(new ThreadStart(delegate
                 {
                         img.Source = bmpImage;
                         img.Unloaded += delegate 
                                 {
                                         ms.Close();
                                         ms.Dispose();
                                 };

                          grdImageContainer.Children.Add(img);
                  }));

     };

new Thread(thread).Start();

直接重新赋值一次就替换了。

这是一个完整的例子:
private void button1_Click(object sender, RoutedEventArgs e)
{
    ThreadPool.QueueUserWorkItem(LoadImage, new LoadImageRequest { ImageName = "Image.png", Control = image1 });
}

private void LoadImage(object state)
{
    var request = (LoadImageRequest)state;

    byte[] data = ...; // load bytes from the database using request.ImageName

    using (var stream = new MemoryStream(data))
    {
        var imageSource = BitmapFrame.Create(stream);

        Dispatcher.BeginInvoke(
            new Action<ImageSource>(p => request.Control.Source = p), imageSource
        );
    }
}

private class LoadImageRequest
{
    public string ImageName;
    public Image Control;
}

 

 
悟行 | 园豆:12559 (专家六级) | 2013-04-29 09:44
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册