问题
On MSDN I found this for the definition of the image stride. In short it is the width in bytes of one line in the buffer.
Now I have an RGB image in a similar buffer and I have been given the stride and the image width in pixels, and I want to know how much padding bytes there have been added.
Is this simply stride - 3 * imagewidth since I have 3 bytes (RGB) per pixel?
unsafe private void setPrevFrame(IntPtr pBuffer)
{
prevFrame = new byte[m_videoWidth, m_videoHeight, 3];
Byte* b = (byte*) pBuffer;
for (int i = 0; i < m_videoWidth; i++)
{
for (int j = 0; j < m_videoHeight; j++)
{
for (int k = 0; k < 3; k++)
{
prevFrame[i,j,k] = *b;
b++;
}
}
b += (m_stride - 3 * m_videoHeight);
}
}
It's the last line of code I'm not sure about
回答1:
Stride will be padded to a 4 byte boundary:
So if your image width is W
and it is 3 bytes per pixel:
int strideWidth = ((W * 3) - 1) / 4 * 4 + 4;
//or simply
int strideWidth = Math.Abs(bData.Stride);
//and so
int padding = strideWidth - W * 3;
If you are using the .Stride property of the BitmapData
object, you must Abs
that value because it may be negative.
Following your edit of the question:
There is no need for you to know the padding in order to iterate all the bytes of the image:
unsafe private void setPrevFrame(IntPtr pBuffer)
{
for (int j = 0; j < m_videoHeight; j++)
{
b = scan0 + j * stride; //the first byte of the first pixel of the row
for (int i = 0; i < m_videoWidth; i++)
{
...
}
}
}
Your previous method will also fail on bottom-up images, as described in the MSDN link you posted.
来源:https://stackoverflow.com/questions/20053958/stride-and-buffersize-when-processing-images