2

How would you convert a Directx11 Texture2d into an image on the cpu that I can process?

I have tried searching the issue and google comes up with unity answers that use exclusive API's or the answers reflect to System.Drawing.Texture2

mrvux
  • 8,523
  • 1
  • 27
  • 61
Mike Hawk
  • 21
  • 2
  • If the texture 2D was created (ID3D11Device::CreateTexture2D) with D3D11_CPU_ACCESS_READ, then you can Map (ID3D11DeviceContext::Map) it directly and copy the bytes. Otherwise you must create another texture 2D with D3D11_CPU_ACCESS_READ, copy it (ID3D11DeviceContext::CopyResource) and Map this new one. I have no idea how to to this with SharpDX which uses its own terminology – Simon Mourier Jul 31 '21 at 05:05

1 Answers1

0

You need to create a staging texture, that you can then access through cpu.

To do so, I assume that you already have an existing SharpDX texture :

    public static StagingTexture2d FromTexture(Texture2D texture)
    {
        if (texture == null)
            throw new ArgumentNullException("texture");

        //Get description, and swap a few flags around (make it readable, non bindable and staging usage)
        Texture2DDescription description = texture.Description;
        description.BindFlags = BindFlags.None;
        description.CpuAccessFlags = CpuAccessFlags.Read;
        description.Usage = ResourceUsage.Staging;

        return new StagingTexture2d(texture.Device, description);
    }

This new texture will allow read operations.

Next you need to copy your GPU texture into the staging Texture using the device context :

deviceContext.CopyResource(gpuTexture, stagingTexture);

Once this is done, you can map the staging texture to access it's content on the CPU :

DataStream dataStream;
DataBox dataBox = deviceContext.MapSubresource(stagingTexture,0, MapMode.Read, MapFlags.None, out dataStream); 

//Use either datastream to read data, or dataBox.DataPointer
//generally it's good to make a copy of that data immediately and unmap asap

//Very important, unmap once you done
deviceContext.UnmapSubresource(stagingTexture, 0);
mrvux
  • 8,523
  • 1
  • 27
  • 61