如何从ID3D11Texture2D访问像素数据?

时间:2017-04-26 09:37:33

标签: c++ windows directx pixel

我正在使用Windows桌面复制API来制作自己的镜像协议。 我有这段代码:

// Get new frame
HRESULT hr = m_DeskDupl->AcquireNextFrame(500, &FrameInfo, &DesktopResource);
if (hr == DXGI_ERROR_WAIT_TIMEOUT)
{
    *Timeout = true;
    return DUPL_RETURN_SUCCESS;
}

以下是FrameInfo结构:

`typedef struct _FRAME_DATA {
ID3D11Texture2D* Frame;
DXGI_OUTDUPL_FRAME_INFO FrameInfo;
_Field_size_bytes_((MoveCount * sizeof(DXGI_OUTDUPL_MOVE_RECT)) +    (DirtyCount * sizeof(RECT))) BYTE* MetaData;
UINT DirtyCount;
UINT MoveCount;
 } FRAME_DATA;`

我想从ID3D11Texture2D* Frame;中提取像素缓冲区 如何在BYTE *unsigned char *上提取并具有RGB序列? 谢谢!

2 个答案:

答案 0 :(得分:6)

您需要使用ID3D11Device::CreateTexture2D创建具有CPU读取访问权限的相同大小的第二个纹理,使用ID3D11DeviceContext::CopyResourceID3D11DeviceContext::CopySubresourceRegion将整个帧或仅更新的部分复制到GPU上的此纹理(可以使用IDXGIOutputDuplication::GetFrameDirtyRectsIDXGIOutputDuplication::GetFrameMoveRects来检索哪些部分已更新,映射第二个纹理以使CPU可以使用ID3D11DeviceContext::Map访问它,这使得D3D11_MAPPED_SUBRESOURCE结构包含指向缓冲区包含帧数据和它的大小,这就是你要找的东西。

Microsoft提供rather detailed Desktop Duplication API usage sample来实现上述所有步骤。

还有straight sample demonstrating how to save ID3D11Texture2D data to file

答案 1 :(得分:2)

您好,这里的代码可以满足您的要求。输出将位于UCHAR缓冲区g_iMageBuffer

//Variable Declaration
IDXGIOutputDuplication* IDeskDupl;
IDXGIResource*          lDesktopResource = nullptr;
DXGI_OUTDUPL_FRAME_INFO IFrameInfo;
ID3D11Texture2D*        IAcquiredDesktopImage;
ID3D11Texture2D*        lDestImage;
ID3D11DeviceContext*    lImmediateContext;
UCHAR*                  g_iMageBuffer=nullptr;

//Screen capture start here
hr = lDeskDupl->AcquireNextFrame(20, &lFrameInfo, &lDesktopResource);

// >QueryInterface for ID3D11Texture2D
hr = lDesktopResource->QueryInterface(IID_PPV_ARGS(&lAcquiredDesktopImage));
lDesktopResource.Release();

// Copy image into GDI drawing texture
lImmediateContext->CopyResource(lDestImage,lAcquiredDesktopImage);
lAcquiredDesktopImage.Release();
lDeskDupl->ReleaseFrame();  

// Copy GPU Resource to CPU
D3D11_TEXTURE2D_DESC desc;
lDestImage->GetDesc(&desc);
D3D11_MAPPED_SUBRESOURCE resource;
UINT subresource = D3D11CalcSubresource(0, 0, 0);
lImmediateContext->Map(lDestImage, subresource, D3D11_MAP_READ_WRITE, 0, &resource);

std::unique_ptr<BYTE> pBuf(new BYTE[resource.RowPitch*desc.Height]);
UINT lBmpRowPitch = lOutputDuplDesc.ModeDesc.Width * 4;
BYTE* sptr = reinterpret_cast<BYTE*>(resource.pData);
BYTE* dptr = pBuf.get() + resource.RowPitch*desc.Height - lBmpRowPitch;
UINT lRowPitch = std::min<UINT>(lBmpRowPitch, resource.RowPitch);

for (size_t h = 0; h < lOutputDuplDesc.ModeDesc.Height; ++h)
{
    memcpy_s(dptr, lBmpRowPitch, sptr, lRowPitch);
    sptr += resource.RowPitch;
    dptr -= lBmpRowPitch;
}

lImmediateContext->Unmap(lDestImage, subresource);
long g_captureSize=lRowPitch*desc.Height;
g_iMageBuffer= new UCHAR[g_captureSize];
g_iMageBuffer = (UCHAR*)malloc(g_captureSize);

//Copying to UCHAR buffer 
memcpy(g_iMageBuffer,pBuf,g_captureSize);