Artem Makarov
Artem Makarov

Reputation: 874

byte[] to ImageSource stream

I need to convert byte[] to BitmapImage and show it in WPF image control. (img.Source = ...).

if i convert it like this:

m_photo = new BitmapImage();

using (MemoryStream stream = new MemoryStream(photo.ToArray()))
{
    m_photo.BeginInit();
    m_photo.StreamSource = stream;
    m_photo.EndInit();
}

it can't do XAML binding to Source property because "m_photo owns another stream"... What can I do?

Upvotes: 1

Views: 765

Answers (2)

Artem Makarov
Artem Makarov

Reputation: 874

Ok, I just found solution. If use this code (converting byte[] to bitmapSource) in code of class - you have this error, that the object is in another stream. But if create a Converter (IValueConverter) and use it with same code of converting in XAML binding - everything ok!

Thanks everybody!

Upvotes: 0

LadderLogic
LadderLogic

Reputation: 1140

Set the cache option to OnLoad after begininit

m_photo.CacheOption = BitmapCacheOption.OnLoad;

EDIT: complete code for bmp array to Image source

                DrawingGroup dGroup = new DrawingGroup();
                using (DrawingContext drawingContext = dGroup.Open())
                {
                    var bmpImage = new BitmapImage();
                    bmpImage.BeginInit();
                    bmpImage.CacheOption = BitmapCacheOption.OnLoad;

                    bmpImage.StreamSource = new MemoryStream(photoArray);
                    bmpImage.EndInit();
                    drawingContext.DrawImage(bmpImage, new Rect(0, 0, bmpImage.PixelWidth, bmpImage.PixelHeight));
                    drawingContext.Close();
                }
                DrawingImage dImage = new DrawingImage(dGroup);
                if (dImage.CanFreeze)
                    dImage.Freeze();
                imageControl.Source = dImage;

Upvotes: 2

Related Questions