c# - 在运行时显示大图像
问题描述
这是问题所在。我有一个视图,应该显示图像和一些控件。用户添加新图像,更改一些选项并单击“完成”。图像很大而且非常大(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;
一切都挂起,直到图像完全加载。
有没有办法在后台加载预览并在没有那些可怕的挂起的情况下显示它?
解决方案
正如您已经提到的,您正在使用图像加载阻塞 UI 线程。您可以使用 WriteableBitmap 类实例作为 Image 的源。这将允许您在后台线程或异步任务上加载图像。这是有关该问题的快速指南(不是我的)。
https://www.i-programmer.info/programming/wpf-workings/527-writeablebitmap.html
推荐阅读
- vue.js - 对于 Vuex Store 中的每个项目,分配一个分数(基于计算),然后按分数排序
- php - 为事件日历插件添加新事件时预填充 post_title 和 post_content
- mongoose - Mongoose:填充嵌套的 id 数组
- php - Wordpress WooCommerce ChargeLogic 测试结帐错误
- ios - 如何使我的 ReferenceWritableKeyPath 类通用
- sql - 对二进制数据字段具有唯一约束的批量插入的最佳数据库
- python - 无法从同一 docker swarm 上运行的其他服务连接到 postgres 服务?
- angular - 登录后重定向用户不更新地址栏
- c++ - 重载运算符>>从二叉树中删除一个节点
- php - Facebook 登录 api 通过 https 使用 localhost