Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Byte[] to BitmapImage

I need help, I have this method to get a BitmapImage from a Byte[]

public BitmapSource ByteToBitmapSource(byte[] image)
{
    BitmapImage imageSource = new BitmapImage();

    using (MemoryStream stream = new MemoryStream(image))
    {
        stream.Seek(0, SeekOrigin.Begin);
        imageSource.BeginInit();
        imageSource.StreamSource = stream;
        imageSource.CacheOption = BitmapCacheOption.OnLoad;
        imageSource.EndInit();
    }

    return imageSource;
}

imageSource.EndInit(); throws an error "We found no imaging component suitable to complete this operation."

like image 611
fma3 Avatar asked Jan 17 '12 15:01

fma3


1 Answers

Set Image.Source to a byte array property in XAML.

<Image x:Name="MyImage" Source="{Binding Path=MyByteArrayProperty}" />

If you really want you can do this in code-behind:

public void DecodePhoto(byte[] byteVal)
{
  BitmapImage myBitmapImage = new BitmapImage();
  myBitmapImage.BeginInit();
  myBitmapImage.StreamSource = new MemoryStream(byteVal);
  myBitmapImage.DecodePixelWidth = 200;
  myBitmapImage.EndInit();
  MyImage.Source = myBitmapImage;
}
like image 148
patrick Avatar answered Sep 25 '22 05:09

patrick