我写了一个简短的示例,它将填充数组的每一行以使其适应所需的格式。它将创建一个 2x2 检查板位图。
byte[] bytes =
{
255, 255, 255,
0, 0, 0,
0, 0, 0,
255, 255, 255,
};
var columns = 2;
var rows = 2;
var stride = columns*4;
var newbytes = PadLines(bytes, rows, columns);
var im = new Bitmap(columns, rows, stride,
PixelFormat.Format24bppRgb,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
PadLines
方法写在下面。我试图通过使用来优化它Buffer.BlockCopy
,以防您的位图很大。
static byte[] PadLines(byte[] bytes, int rows, int columns)
{
//The old and new offsets could be passed through parameters,
//but I hardcoded them here as a sample.
var currentStride = columns*3;
var newStride = columns*4;
var newBytes = new byte[newStride*rows];
for (var i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride*i, newBytes, newStride * i, currentStride);
return newBytes;
}