计算WriteableBitmap.WritePixels方法所需的缓冲区大小

JMK*_*JMK 16 c# wpf buffer writeablebitmap

如何计算WriteableBitmap.WritePixels方法所需的缓冲区大小?

我使用带有四个参数的重载,第一个是Int32Rect,下一个是包含颜色的RGBA数字的字节数组,第三个是步幅(这是我的可写位图的宽度乘以每像素的位数除以通过8),最后一个是缓冲区(在Intellisense中称为偏移).

我在下面的代码中得到缓冲区大小不足够的运行时错误:

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);
Run Code Online (Sandbox Code Playgroud)

我需要使用什么公式来计算上面代码中所需的缓冲区值?

Cle*_*ens 13

步幅值计算为写入矩形中每个"像素行"的字节数:

var stride = (rect.Width * bitmap.Format.BitsPerPixel + 7) / 8;
Run Code Online (Sandbox Code Playgroud)

所需的缓冲区大小是每行的字节数乘以行数:

var bufferSize = rect.Height * stride;
Run Code Online (Sandbox Code Playgroud)

如果你有一个2x2的写矩形和一个32位的每像素格式,例如PixelFormats.Pbgra32,你得到stride8,bufferSize 得到16.