【发布时间】:2011-07-05 21:16:51
【问题描述】:
如何使用 c# 在 WPF 中从 MemoryStream 获取 ImageSource ?或将MemoryStream 转换为ImageSource 以在wpf 中将其显示为图像?
【问题讨论】:
标签: c# wpf memorystream imagesource
如何使用 c# 在 WPF 中从 MemoryStream 获取 ImageSource ?或将MemoryStream 转换为ImageSource 以在wpf 中将其显示为图像?
【问题讨论】:
标签: c# wpf memorystream imagesource
using (MemoryStream memoryStream = ...)
{
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = memoryStream;
imageSource.EndInit();
// Assign the Source property of your image
image.Source = imageSource;
}
【讨论】:
Image.Source 之前处理了流,则除了@Darin Dimitrov 答案之外,什么都不会显示,所以要小心
例如,Next 方法将不起作用,From one of my projects using LiteDB
public async Task<BitmapImage> DownloadImage(string id)
{
using (var stream = new MemoryStream())
{
var f = _appDbManager.DataStorage.FindById(id);
f.CopyTo(stream);
var imageSource = new BitmapImage {CacheOption = BitmapCacheOption.OnLoad};
imageSource.BeginInit();
imageSource.StreamSource = stream;
imageSource.EndInit();
return imageSource;
}
}
你不能使用最后一个函数返回的imageSource
但是这个实现会起作用
public async Task<BitmapImage> DownloadImage(string id)
{
// TODO: [Note] Bug due to memory leaks, if we used Using( var stream = new MemoryStream()), we will lost the stream, and nothing will shown
var stream = new MemoryStream();
var f = _appDbManager.DataStorage.FindById(id);
f.CopyTo(stream);
var imageSource = new BitmapImage {CacheOption = BitmapCacheOption.OnLoad};
imageSource.BeginInit();
imageSource.StreamSource = stream;
imageSource.EndInit();
return imageSource;
}
【讨论】: