2017-04-26 787 views
1

我使用Windows Desktop Duplication API来制作自己的镜像协议。 我有这样一段代码:如何从ID3D11Texture2D访问像素数据?

// 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序列? 谢谢!

回答

3

您需要创建使用ID3D11Device::CreateTexture2D CPU读取访问相同尺寸的第二质感,使用ID3D11DeviceContext::CopyResourceID3D11DeviceContext::CopySubresourceRegion整个帧或刚刚更新了部分复制到这个纹理上的GPU(也可以检索使用IDXGIOutputDuplication::GetFrameDirtyRects哪些部分进行了更新和IDXGIOutputDuplication::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

嗨,这里是帮助您的要求的代码。输出将在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);