首页 > 解决方案 > C#texture2d如何转换为cpu图像

问题描述

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

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

标签: c#imagedirectx-11sharpdxtexture2d

解决方案


您需要创建一个暂存纹理​​,然后您可以通过 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);

推荐阅读