首页 > 解决方案 > 在运行时显示大图像

问题描述

这是问题所在。我有一个视图,应该显示图像和一些控件。用户添加新图像,更改一些选项并单击“完成”。图像很大而且非常大(400-1500 MB Tiff) 用户应该可以看到图像的预览,但是如果它加载 10-15 秒甚至更长时间也没关系,他这次有工作。图像通过MVVM简单字符串等模式绑定(文件将始终在本地文件夹中)

<Image Name="ImagePreview" Source="{Binding SFilePathForPreview,
         FallbackValue={StaticResource DefaultImage},
         TargetNullValue={StaticResource DefaultImage}}"
         HorizontalAlignment="Center" Width="200" Height="200"
         VerticalAlignment="Center" />

问题是当用户尝试添加文件以进行加载时,一切都挂起。我知道这种情况应该通过多线程来解决 - 但不知道如何实现这一点。

我试图从不同线程的视图中更新图像,如下所示:

Thread newThread = new Thread(LazyLoad);
newThread.Name = "LazyLoad";
newThread.Start(SFilePathForPreview);

public void LazyLoad(object SFilePath)
{            
    try
    {
        string path = (string)SFilePath;

        BitmapImage t_source = new BitmapImage();

        t_source.BeginInit();
        t_source.UriSource = new Uri(path);
        t_source.DecodePixelWidth = 200;
        t_source.EndInit();

        t_source.Freeze();
        this.Dispatcher.Invoke(new Action(delegate
        {
            ImagePreview.Source = t_source;
        }));
    }
    catch
    {
        //...
    }
}

但无论如何

ImagePreview.Source = t_source;

一切都挂起,直到图像完全加载。

有没有办法在后台加载预览并在没有那些可怕的挂起的情况下显示它?

标签: c#wpfimagemvvmlarge-files

解决方案


正如您已经提到的,您正在使用图像加载阻塞 UI 线程。您可以使用 WriteableBitmap 类实例作为 Image 的源。这将允许您在后台线程或异步任务上加载图像。这是有关该问题的快速指南(不是我的)。

https://www.i-programmer.info/programming/wpf-workings/527-writeablebitmap.html


推荐阅读