简体   繁体   English

从 c# wpf 中的 Memorystream 获取 Imagesource

[英]Get Imagesource from Memorystream in c# wpf

How can I get ImageSource from MemoryStream in WPF using c#?如何使用 c# 从 WPF 中的MemoryStream获取ImageSource or convert MemoryStream to ImageSource to display it as image in wpf?或将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;
}
Additional to @Darin Dimitrov answer if you disposed the stream before assigning to Image.Source nothing will show, so be careful 如果您在分配给Image.Source之前处置了 stream ,则除了@Darin Dimitrov 答案之外,什么都不会显示,所以要小心

For example, the Next method will not work, From one of my projects using LiteDB例如,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; } }

you can not use returned imageSource from the last function你不能使用从最后一个 function 返回的imageSource

But this implementation will work但是这个实现会起作用

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM