Search code examples
c++directxdirectx-11texture2drender-to-texture

How to get the DirectX::Image (from DirectXTex) structure based on ID3D11Texture2D?


I have an custom texture class:

class Texture{
    ID3D11Texture2D * renderTargetTexture;
public:
    ...
    void saveToTGA(std::wstring filePath);
};

I am using this texture as render target between render passes. I want to write the saveToTGA(std::wstring filePath) method which saves the texture to file (kind of a screenshot).

MSDN says that D3DX11SaveTextureToFile(...) is depreciated so I decided to use DirectXTex library as they suggested.

I know I have to use:

DirectX::Image image = ...
DirectX::SaveToTGAFile(image, filePath.c_str());

But the problem is: how to get the DirectX::Image (from DirectXTex) structure based on ID3D11Texture2D ?


Solution

  • From MSDN document you could use

    Blockquote we recommend that you use the DirectXTex library, CaptureTexture then SaveToXXXFile (where XXX is WIC, DDS, or TGA; WIC doesn't support DDS and TGA; D3DX 9 supported TGA as a common art source format for games).

    So, first you capture your texture from the texture buffer using

    HRESULT hr = DirectX::CaptureTexture(m_D3D->GetDevice(), m_D3D->GetDeviceContext(), resourceContext, image);
    

    and follow with Save function

    hr = DirectX::SaveToDDSFile(image.GetImages(),image.GetImageCount(), image.GetMetadata(), DirectX::DDS_FLAGS_NONE, Filename);
    

    Please see this reference https://github.com/Microsoft/DirectXTex/wiki/CaptureTexture