从媒体缓冲区读取-指针算术C++语法

Read From Media Buffer - Pointer Arithmetic C++ Syntax

本文关键字:C++ 语法 指针 媒体 缓冲区 读取      更新时间:2023-10-16

这可能以前就出现过,但下面的代码取自我正在修改的MSDN示例。我想知道如何迭代缓冲区的内容,其中包含位图的数据并打印出颜色。每个像素是4个字节的数据,所以我假设R G B值占这些字节中的3个,可能A是第4个。

所需的指针算术(理想情况下在循环中(的正确C++语法是什么,它将把迭代过程中指向的值存储到我可以使用的局部变量中,例如打印到控制台。

非常感谢

PS。这安全吗?或者有没有更安全的方法来读取IMFMediaBuffer的内容?我找不到其他选择。

这是代码:

hr = pSample->ConvertToContiguousBuffer(&pBuffer); // this is the BitmapData
    // Converts a sample with multiple buffers into a sample with a single IMFMediaBuffer which we Lock in memory next...
    // IMFMediaBuffer represents a block of memory that contains media data
    hr = pBuffer->Lock(&pBitmapData, NULL, &cbBitmapData);  // pBuffer is IMFMediaBuffer
    /* Lock method gives the caller access to the memory in the buffer, for reading or writing:
    pBitmapData - receives a pointer to start of buffer
    NULL - receives the maximum amount of data that can be written to the buffer. This parameter can be NULL.
    cbBitmapData - receives the length of the valid data in the buffer, in bytes. This parameter can be NULL.
    */

我自己解决了这个问题,并认为最好在这里添加答案,这样它就可以正确格式化,也许其他人也会从中受益。基本上,在这种情况下,我们使用32位的图像数据,最棒的是,我们从内存中读取原始数据,因此还没有可以跳过的位图标头,因为这只是原始颜色信息。

注意:在这4个字节中,我们有(从0-31位(B G R A,我们可以使用我的代码进行验证:

  int x = 0;
    while(x < cbBitmapData){
        Console::Write("B: {0}", (*(pBitmapData + x++)));
        Console::Write("tG: {0}", (*(pBitmapData + x++)));
        Console::Write("tR: {0}", (*(pBitmapData + x++)));
        Console::Write("tA: {0}n", (*(pBitmapData + x++)));
    }

从输出中,您将看到每个像素的A值为0,因为这里没有透明度或深度的概念,这正是我们所期望的。

此外,为了验证我们在缓冲区中的所有数据都是原始图像数据,而没有其他数据,我使用了这个计算,你可能也会发现它很有用:

Console::Write("no of pixels in buffer: {0} nexpected no of pixels based on dimensions:{1}", (cbBitmapData/4), (m_format.imageWidthPels * m_format.imageHeightPels) );

其中,我们将cbBitmapData的值除以4,因为它是字节数,并且如上所述,对于每个像素,我们有4个字节的宽度(事实上是32位DWORDS,因为字节的长度显然在硬件之间并不总是严格一致!?(。我们将其与图像宽度乘以其高度进行比较。它们是相等的,因此我们在缓冲区中只有像素颜色信息。

希望这能帮助到别人。