开发者

Get Imagesource from Memorystream in c# wpf

开发者 https://www.devze.com 2023-03-17 06:39 出处:网络
How c开发者_JAVA百科an I get ImageSource from MemoryStream in WPF using c# ? or convert MemoryStream to ImageSource to display it as image in wpf ?using (MemoryStream memoryStream = ...)

How c开发者_JAVA百科an 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;
}


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消