How do I calculate the required buffer size for the WriteableBitmap.WritePixels method?
I am using the overload taking four parameters, the first is an Int32Rect, the next is a byte array containing the RGBA numbers for the colour, the third is the stride (which is the width of my writeable bitmap multiplied by the bits per pixel divided by 8), and the last is the buffer (referred to as the offset in Intellisense).
I am getting the Buffer size is not sufficient runtime error in the below code:
byte[] colourData = { 0, 0, 0, 0 };
var xCoordinate = 1;
var yCoordinate = 1;
var width = 2;
var height = 2;
var rect = new Int32Rect(xCoordinate, yCoordinate, width, height);
var writeableBitmap = new WriteableBitmap(MyImage.Source as BitmapSource);
var stride = width*writeableBitmap.Format.BitsPerPixel/8;
writeableBitmap.WritePixels(rect, colourData, stride,0);
What is the formula I need to use to calculate the buffer value needed in the above code?
The stride value is calculated as the number of bytes per "pixel line" in the write rectangle:
var stride = (rect.Width * bitmap.Format.BitsPerPixel + 7) / 8;
The required buffer size is the number of bytes per line multiplied by the number of lines:
var bufferSize = rect.Height * stride;
Provided that you have a 2x2 write rectangle and a 32-bits-per-pixel format, e.g. PixelFormats.Pbgra32
, you get stride
as 8 and bufferSize as 16.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With