【问题标题】:C# texture2d how to convert to cpu imageC#texture2d如何转换为cpu图像
【发布时间】:2021-10-06 10:24:30
【问题描述】:

如何将 Directx11 Texture2d 转换为 cpu 上我可以处理的图像?

我已尝试搜索该问题,谷歌提出了使用专有 API 的统一答案或反映到 System.Drawing.Texture2 的答案

【问题讨论】:

  • 如果纹理 2D 是使用 D3D11_CPU_ACCESS_READ 创建的 (ID3D11Device::CreateTexture2D),那么您可以直接映射 (ID3D11DeviceContext::Map) 并复制字节。否则,您必须使用 D3D11_CPU_ACCESS_READ 创建另一个 2D 纹理,复制它 (ID3D11DeviceContext::CopyResource) 并映射这个新纹理。我不知道如何使用使用自己的术语的 SharpDX 来做到这一点

标签: c# image directx-11 sharpdx texture2d


【解决方案1】:

您需要创建一个暂存纹理​​,然后您可以通过 cpu 访问它。

为此,我假设您已经拥有一个现有的 SharpDX 纹理:

    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);
    }

这个新纹理将允许读取操作。

接下来,您需要使用设备上下文将 GPU 纹理复制到暂存纹理中:

deviceContext.CopyResource(gpuTexture, stagingTexture);

完成后,您可以映射暂存纹理以访问其在 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多