2017-04-26 800 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);