Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the required buffer size for the WriteableBitmap.WritePixels method

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?

like image 385
JMK Avatar asked Dec 19 '12 13:12

JMK


1 Answers

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.

like image 128
Clemens Avatar answered Oct 10 '22 21:10

Clemens