[C++] DirectX 11 : Get Image Data(Byte array) from ID3D11ShaderResourceView
BYTE* GetImageData(ID3D11Device* device, ID3D11DeviceContext* context, ID3D11ShaderResourceView* shaderResourceView, /*OUT*/ int* nWidth, /*OUT*/ int* nHeight)
{
ID3D11Resource* resource = NULL;;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
if (shaderResourceView)
{
shaderResourceView->GetResource(&resource);
shaderResourceView->GetDesc(&srvDesc);
}
else
return NULL;
ID3D11Texture2D* tex = (ID3D11Texture2D*)resource;
if (tex)
{
D3D11_TEXTURE2D_DESC description;
tex->GetDesc(&description);
description.BindFlags = 0;
description.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
description.Usage = D3D11_USAGE_STAGING;
ID3D11Texture2D* texTemp = NULL;
HRESULT hr = device->CreateTexture2D(&description, NULL, &texTemp);
if (FAILED(hr))
{
if (texTemp)
{
texTemp->Release();
texTemp = NULL;
}
return NULL;
}
context->CopyResource(texTemp, tex);
D3D11_MAPPED_SUBRESOURCE mapped;
unsigned int subresource = 0
hr = context->Map(texTemp, 0, D3D11_MAP_READ, 0, &mapped);
if (FAILED(hr))
{
texTemp->Release();
texTemp = NULL;
return NULL;
}
*nWidth = description.Width;
*nHeight = description.Height;
const int pitch = mapped.RowPitch;
BYTE* source = (BYTE*)(mapped.pData);
BYTE* dest = new BYTE[(*nWidth)*(*nHeight) * 4];
BYTE* destTemp = dest;
for (int i = 0; i < *nHeight; ++i)
{
memcpy(destTemp, source, *nWidth * 4);
source += pitch;
destTemp += *nWidth * 4;
}
context->Unmap(texTemp, 0);
return dest;
}
else
return NULL;
}