在c#wpf中从Memorystream获取Imagesource

时间:2011-07-05 21:16:51

标签: c# wpf memorystream imagesource

如何使用c#在WPF中从ImageSource获取MemoryStream?或将MemoryStream转换为ImageSource以在wpf中将其显示为图像?

2 个答案:

答案 0 :(得分:44)

using (MemoryStream memoryStream = ...)
{
    var imageSource = new BitmapImage();
    imageSource.BeginInit();
    imageSource.StreamSource = memoryStream;
    imageSource.EndInit();

    // Assign the Source property of your image
    image.Source = imageSource;
}

答案 1 :(得分:1)

如果您在分配给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;
}