1

I read all first page results of "Byte array to BitmapImage" and I fount Byte array to BitmapImage WP byte[] to BitmapImage in silverlight the problem is that I code dosen't work for me and I get this error:

'System.Windows.Media.Imaging.BitmapImage' does not contain a definition for 'SetSource' and no extension method 'SetSource' accepting a first argument of type 'System.Windows.Media.Imaging.BitmapImage' could be found (are you missing a using directive or an assembly reference?)

My main code is:

int stride = CoverPhotoBitmap.PixelWidth * 4;
int size = CoverPhotoBitmap.PixelHeight * stride;
byte[] CoverPhotoPixels = new byte[size];
CoverPhotoBitmap.CopyPixels(CoverPhotoPixels, stride, 0);

byte[] HiddenPhotoPixels = new byte[size];
HiddenPhotoBitmap.CopyPixels(HiddenPhotoPixels, stride, 0);
ResultPhotoBitmap = ByteArraytoBitmap(HiddenPhotoPixels);

and my method is:

public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
    MemoryStream stream = new MemoryStream(byteArray);
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.SetSource(stream);
    return bitmapImage;
}
Community
  • 1
  • 1
  • How you want to use this bitmap, do you want to set it to Image control? – Amer Zafar Jan 08 '15 at 12:44
  • You want to set the `Source` property instead of calling the `SetSource` method of the Silverlight BitmapImage. Anyway, that won't help, because it required an encoded image buffer (like PNG or JPEG) which you don't have. You'll have to create a `BitmapSource` from the byte array, or write a byte array to a `WriteableBitmap`. – Clemens Jan 08 '15 at 12:48
  • @Amer Zafar Yes I want to use it as an Image control – Mostafa Mohammadi Jan 08 '15 at 16:41
  • @Clemens As you see I used the question that Jcl suggest to me and solved my later question, my current question is what is SetSource alternative in WPF. – Mostafa Mohammadi Jan 08 '15 at 16:51

1 Answers1

3

The example you found appears to have been specific to Silverlight. The exception explains that the method you called(SetSource) does not exist. What you need to do is set the StreamSource.

public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
    MemoryStream stream = new MemoryStream(byteArray);

    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.StreamSource = stream;
    bitmapImage.EndInit();

    return bitmapImage;
}
Derrick Moeller
  • 4,808
  • 2
  • 22
  • 48
  • Now I get this error: An unhandled exception of type 'System.NotSupportedException' occurred in PresentationCore.dll Additional information: No imaging component suitable to complete this operation was found. – Mostafa Mohammadi Jan 08 '15 at 15:18