13

使用 WPF 在 C# 中异步加载 BitmapImage 的最佳方法是什么?

4

6 回答 6

7

我只是在研究这个,不得不投入我的两分钱,尽管在最初的帖子之后几年(以防万一其他人来寻找我正在研究的同样的事情)。

我有一个Image控件,需要使用Stream在后台加载它的图像,然后显示。

我一直遇到的问题是BitmapSource,它的Stream源和Image控件都必须在同一个线程上。

在这种情况下,使用 Binding 并将其设置为 IsAsynch = true 将引发跨线程异常。

BackgroundWorker 非常适合 WinForms,您可以在 WPF 中使用它,但我更愿意避免在 WPF 中使用 WinForm 程序集(不建议项目膨胀,这也是一个很好的经验法则)。在这种情况下,这也应该抛出一个无效的交叉引用异常,但我没有测试它。

事实证明,一行代码将使这些工作中的任何一个工作:

//Create the image control
Image img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};

//Create a seperate thread to load the image
ThreadStart thread = delegate
     {
         //Load the image in a seperate thread
         BitmapImage bmpImage = new BitmapImage();
         MemoryStream ms = new MemoryStream();

         //A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(@"C:\ImageFileName.jpg", FileMode.Open);
         MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);

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

         //**THIS LINE locks the BitmapImage so that it can be transported across threads!! 
         bmpImage.Freeze();

         //Call the UI thread using the Dispatcher to update the Image control
         Dispatcher.BeginInvoke(new ThreadStart(delegate
                 {
                         img.Source = bmpImage;
                         img.Unloaded += delegate 
                                 {
                                         ms.Close();
                                         ms.Dispose();
                                 };

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

     };

//Start previously mentioned thread...
new Thread(thread).Start();
于 2010-04-20T06:11:08.687 回答
3

假设您正在使用数据绑定,将Binding.IsAsync属性设置为 True 似乎是实现此目的的标准方法。如果您使用后台线程 + Dispatcher 对象在代码隐藏文件中加载位图是更新 UI 异步的常用方法

于 2008-08-31T10:34:46.857 回答
3

这将允许您通过使用 HttpClient 进行异步下载,在 UI 线程上创建 BitmapImage:

private async Task<BitmapImage> LoadImage(string url)
{
    HttpClient client = new HttpClient();

    try
    {
        BitmapImage img = new BitmapImage();
        img.CacheOption = BitmapCacheOption.OnLoad;
        img.BeginInit();
        img.StreamSource = await client.GetStreamAsync(url);
        img.EndInit();
        return img;
    }
    catch (HttpRequestException)
    {
        // the download failed, log error
        return null;
    }
}
于 2016-06-09T22:51:49.860 回答
2

为了详细说明 aku 的答案,这里有一个关于在哪里设置 IsAsync 的小例子:

ItemsSource="{Binding IsAsync=True,Source={StaticResource ACollection},Path=AnObjectInCollection}"

这就是您将在 XAML 中执行的操作。

于 2009-04-23T21:36:49.423 回答
2
 BitmapCacheOption.OnLoad

var bmp = await System.Threading.Tasks.Task.Run(() => 
{ 
BitmapImage img = new BitmapImage(); 
img.BeginInit(); 
img.CacheOption = BitmapCacheOption.OnLoad; 
img.UriSource = new Uri(path); 
img.EndInit(); 
ImageBrush brush = new ImageBrush(img); 

}
于 2013-10-19T20:07:24.217 回答
0

使用或扩展 System.ComponentModel.BackgroundWorker:http:
//msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

就个人而言,我发现这是在客户端应用程序中执行异步操作的最简单方法。(我在 WinForms 中使用过这个,但不是 WPF。我假设这也适用于 WPF。)

我通常会扩展 Backgroundworker,但您不必这样做。

public class ResizeFolderBackgroundWorker : BackgroundWorker
{

    public ResizeFolderBackgroundWorker(string sourceFolder, int resizeTo)
    {
        this.sourceFolder = sourceFolder;
        this.destinationFolder = destinationFolder;
        this.resizeTo = resizeTo;

        this.WorkerReportsProgress = true;
        this.DoWork += new DoWorkEventHandler(ResizeFolderBackgroundWorker_DoWork);
    }

    void ResizeFolderBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(sourceFolder);
        FileInfo[] files = dirInfo.GetFiles("*.jpg");


        foreach (FileInfo fileInfo in files)
        {
            /* iterate over each file and resizing it */
        }
    }
}

这是您在表单中使用它的方式:

    //handle a button click to start lengthy operation
    private void resizeImageButtonClick(object sender, EventArgs e)
    {
        string sourceFolder = getSourceFolderSomehow();
        resizer = new ResizeFolderBackgroundWorker(sourceFolder,290);
        resizer.ProgressChanged += new progressChangedEventHandler(genericProgressChanged);
        resizer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(genericRunWorkerCompleted);

        progressBar1.Value = 0;
        progressBar1.Visible = true;

        resizer.RunWorkerAsync();
    }

    void genericRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        progressBar1.Visible = false;
        //signal to user that operation has completed
    }

    void genericProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
        //I just update a progress bar
    }
于 2008-09-02T21:57:32.050 回答