0

In my wpf application I get a byte array of a bmp file.

I want to create a new System.Windows.Media.Imaging.BitmapImage.

I created MemoryStream from the byte array, but it doesn't work with SetSource.

Any suggestions ?

Or Cohen
  • 13
  • 3

1 Answers1

0

Add reference:

using System.IO;

Use the following code.

MemoryStream ms = new MemoryStream(imageArray);
Image image = Image.FromStream(ms);

For WPF

public static BitmapImage GetBitmapImage(byte[] imageArray)
{
    using (var stream = new MemoryStream(imageArray))
    {
        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
        return bitmapImage;
    }
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
LPs
  • 16,045
  • 8
  • 30
  • 61
  • 1
    you should improve your answer using the `using` keyword, because MemoryStream is disposable – Steve B Jan 08 '15 at 08:38
  • 3
    He means: using MemoryStream ms = new MemoryStream(imageArray){Image image = Image.FromStream(ms);} – Eric Bole-Feysot Jan 08 '15 at 08:43
  • I think is better to add using at the top to be able to use it for thee whole code. I think after loaded the bmp will be also reversed to byteArray... – LPs Jan 08 '15 at 08:46
  • Thank you for the answer but i'm using wpf and i the Image object you mean is from System.Drawing, and i cannot insert it to the image control in the xaml code. – Or Cohen Jan 08 '15 at 08:49
  • @EricBole-Feysot: this is exactly what I meant. – Steve B Jan 08 '15 at 09:00
  • Thank you its work great !! There is also a solution for silverlight ? – Or Cohen Jan 08 '15 at 09:12
  • I found this [link](http://stackoverflow.com/questions/3335819/byte-to-bitmapimage-in-silverlight) – LPs Jan 08 '15 at 09:15
  • @OrCohen In Silverlight you would use the [SetSource](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.setsource(v=vs.95).aspx) method. – Clemens Jan 08 '15 at 09:18
  • @Clemens The problem with set source is that its not recognize byte array of a bmp file, only gif png and gpeg. Thats why im in problem. – Or Cohen Jan 08 '15 at 09:21
  • 1
    @LPs MemoryStream is an IDisposable and should therefore be disposed, preferably by means of a `using` block. – Clemens Jan 08 '15 at 09:23
  • @OrCohen How about [this suggestion](http://stackoverflow.com/a/6734402/1136211)? – Clemens Jan 08 '15 at 09:34