Search code examples
c++graphicsdirectxdirectx-11texture-mapping

DirectX11 How to CreateTexture2D from unsigned char * data


I have a function GetCamImage that returns the image from camera as:

unsigned char* p = GetCamImage(...);

I need to create ID3D11Texture2D from this data. How can I do it in DirectX 11?

Thanks


Solution

  • It depends on what the format of the actual content in that p is, as well as the width, height, and stride. Assuming the image is an RGBA 32-bit format with simple byte pitch alignment and sized as w by h, then it would be something simple like:

    D3D11_SUBRESOURCE_DATA initData = {0};
    initData.pSysMem = (const void*)p;
    initData.SysMemPitch = w * 4;
    initData.SysMemSlicePitch = h * w * 4;
    
    D3D11_TEXTURE2D_DESC desc;
    desc.Width = w;
    desc.Height = h;
    desc.MipLevels = 1;
    desc.ArraySize = 1;
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;
    desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    desc.CPUAccessFlags = 0;
    
    ID3D11Texture2D* tex = nullptr;
    HRESULT hr = d3dDevice->CreateTexture2D( &desc, &initData, &tex );
    if (FAILED(hr))
       ...