如何使用 c#ImageSource
从MemoryStream
WPF 中获取?或转换MemoryStream
为ImageSource
在 wpf 中将其显示为图像?
问问题
30126 次
2 回答
56
using (MemoryStream memoryStream = ...)
{
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = memoryStream;
imageSource.EndInit();
// Assign the Source property of your image
image.Source = imageSource;
}
于 2011-07-05T21:22:02.613 回答
3
如果您在分配给任何内容之前处置了流,则除了@Darin Dimitrov 答案之外,
Image.Source
将显示任何内容,所以要小心
例如,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;
}
于 2020-10-02T18:37:52.483 回答