mgphall
mgphall

Reputation: 87

Create a WriteableBitmap from a byte array wpf

from examples I have been able to create BitmapImage the byte array

public byte[] BufferFromImage(BitmapImage myImageFile)
{
    WriteableBitmap btmMap = new WriteableBitmap(BitmapFactory.ConvertToPbgra32Format(myImageFile));
    return btmMap.ToByteArray();
}

Now I’m looking to reverse that, but so far without success , I’ve checked on https://writeablebitmapex.codeplex.com which states it can Create a WriteableBitmap from a byte array but I haven’t found any examples.

public WriteableBitmap ByteArrayToImage(Byte[] BArray)
{

    var width = 100;  
    var height = 100;  
    var dpiX = 96d;
    var dpiY = 96d;
    var pixelFormat = PixelFormats.Pbgra32;  
    var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8;
    var stride = bytesPerPixel * width;

    var bitmap = BitmapImage.Create(width, height, dpiX, dpiY, pixelFormat, null, BArray, stride);
    WriteableBitmap wbtmMap = new WriteableBitmap(BitmapFactory.ConvertToPbgra32Format(bitmap));
    return wbtmMap;
}

This returns an error

System.ArgumentException was unhandled by user code Message=Buffer size is not sufficient.

I hoping someone can point me in the right direction cheers

Upvotes: 1

Views: 6072

Answers (1)

cKNet
cKNet

Reputation: 655

Try to increase the buffer's size... Buffer size should be calculated like stride * height.

Upvotes: 3

Related Questions