[英]Get Imagesource from Memorystream in c# wpf
如何使用 c# 从 WPF 中的MemoryStream
获取ImageSource
? 或将MemoryStream
转换为ImageSource
以在 wpf 中将其显示为图像?
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
之前处置了 stream ,则除了@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; } }
你不能使用从最后一个 function 返回的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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.