Mostafa Mohammadi
Mostafa Mohammadi

Reputation: 11

WPF Byte array to BitmapImage

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;
}

Upvotes: 1

Views: 1999

Answers (1)

Derrick Moeller
Derrick Moeller

Reputation: 4950

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;
}

Upvotes: 3

Related Questions