在尝试更好地理解位图和锁定位的所有属性时,我创建了一个 10x1px 图像,具有以下属性:
像素格式:Format24bppRgb
Specifies that the format is 24 bits per pixel; 8 bits each are used for the red, green, and blue components.
颜色深度(以位为单位):24(3 个字节)
这意味着我有 10 个像素,每个像素需要 3 个字节,这意味着我需要创建一个长度为 30 的字节数组来使用以下命令复制所有图像数据:
Marshal.Copy(lockedBitmapData.Scan0, bytesArray, 0, 30);
The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary.
这是否意味着当我访问 BitmapData.Stride
时,它将始终返回一个整数,就好像 PixelFormat 是 32bit
变体之一一样?
为什么下面的代码会导致 2 个额外的字节为 0,而不是 10 个字节为 0?或者它是 2,因为它将 30 字节四舍五入为 32 作为最接近的字节长度,如文档所述,可被 4 整除?我想我误解了文档并期望它在计算步幅时为每个像素计算 4 个字节。
byte[] bytesArray = new byte[lockedBitmapData.Stride];
Marshal.Copy(lockedBitmapData.Scan0, bytesArray, 0, lockedBitmapData.Stride);
最佳答案
步幅被理解为线与线之间的距离,而不是像素与像素之间的距离。与预期的 pixels_per_line * bytes_per_pixel
的差异是由于每个逻辑行末尾的填充造成的。因此你的第二种解释基本上是正确的,
32 as the closest byte length that is divisible by 4 as the doc says
我只是添加“填充以确保完整的 4 字节边界”,因为 16 和 24 也能被 4 整除。 This article包含图片,this answer包含补充信息。
根本原因与硬件有关。如果二维数据结构是内存对齐的(在本例中为 DWORD 对齐),则对该数据的查找(索引)和批量操作的运行速度会显着加快。
关于c# - BitmapData.Stride 与 GetPixelFormatSize(BitmapData.PixelFormat) 除以 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60138664/