'Improve speed saving texture to file using Directx 11 c++

I have a DirectX11 based render, and I need to save a lot of rendered images to hard disk. I have used SaveWICTextureToFile but takes 0.2 seconds to save each image. Images are saved in resolution 1024x768.

Here it is the code to save the images:

    ComPtr<ID3D11Texture2D> backBuffer;
                HRESULT hr = _swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(backBuffer.GetAddressOf()));
                throwIfFail(hr, "Unable to get a buffer");
#ifdef LOG
                auto end = high_resolution_clock::now();
                wchar_t str[256];
                auto tmp = end;
#endif
                hr = SaveWICTextureToFile(_context.Get(), backBuffer.Get(), GUID_ContainerFormatJpeg, w.c_str()/*,&GUID_WICPixelFormat32bppBGRA*/);
                //hr = SaveDDSTextureToFile(_context.Get(), backBuffer.Get(), w.c_str()/*,&GUID_WICPixelFormat32bppBGRA*/);
#ifdef LOG
                end = high_resolution_clock::now();
                wsprintf(str, L"DXRender::saveLastRenderToFile: %d \n", duration_cast<microseconds>(end - tmp).count());
                OutputDebugString(str);
                tmp = end;
#endif
                throwIfFail(hr, "Unable to save buffer");

How can I reduce the time it takes to save each image?



Solution 1:[1]

I have tested the libJPEG and libPNG libraries to save images, and it work fine and faster than SaveWICToTextureFile, the only trick here is that need to be in account the format of the DirectX texture.. Example: Texture format: B8G8R8A8 Then to access to each color need to get the n-th 8 bits to get each channel.. This is the only trick here..

Example:

auto lastText = _textureDesc;
_inputTexture->GetDesc(&_textureDesc);

unsigned char r, g, b;

int _textureRowSize = _mappedResource.RowPitch / sizeof(unsigned char);

int hIdx = 0;
for (int i = 0; i < _textureDesc.Height; ++i)
{
    int wIdx = 0;
    for (int j = 0; j < _textureDesc.Width; ++j)
    {
        r = (unsigned char)textPtr[hIdx + wIdx + 2];
        g = (unsigned char)textPtr[hIdx + wIdx + 1];
        b = (unsigned char)textPtr[hIdx + wIdx];
        
        //do whatever you want with this values...
        
        wIdx += 4;
    }
    hIdx += _textureRowSize;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KronuZ