How can I get ImageSource from MemoryStream in WPF using c# ? or convert MemoryStream to ImageSource to display it as image in 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 nothing will show, so be careful
For example, the Next method will not work, 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
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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With