1

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?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Artem Makarov
  • 874
  • 3
  • 14
  • 25
  • You create two memory streams, wth, wasn't that supposed to be `m_photo.StreamSource = stream;`? – H.B. Aug 16 '12 at 00:30
  • That's my fault :) I'm using only one MemoryStream of course, just Copy-Past problems.. And same problem – Artem Makarov Aug 16 '12 at 00:33
  • @ArtemMakarov I've edited the question to reflect what you said. Does `photo.ToArray()` actually contain an encoded bitmap image (e.g. a PNG) or is it perhaps a pixel array? – Clemens Aug 16 '12 at 06:16
  • 1
    Possible duplicate of [How to convert ImageSource to Byte array?](https://stackoverflow.com/questions/26814426/how-to-convert-imagesource-to-byte-array) – NoWar Nov 09 '17 at 02:31

2 Answers2

1

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;
LadderLogic
  • 1,090
  • 9
  • 17
0

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!

Artem Makarov
  • 874
  • 3
  • 14
  • 25