Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Imagesource from Memorystream in c# wpf

How can I get ImageSource from MemoryStream in WPF using c# ? or convert MemoryStream to ImageSource to display it as image in wpf ?

like image 856
kartal Avatar asked Jul 05 '11 21:07

kartal


2 Answers

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

    // Assign the Source property of your image
    image.Source = imageSource;
}
like image 83
Darin Dimitrov Avatar answered Oct 03 '22 20:10

Darin Dimitrov


Additional to @Darin Dimitrov answer if you disposed the stream before assigning to 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;
}
like image 3
Al Banna Techno logy Avatar answered Oct 03 '22 19:10

Al Banna Techno logy