directx-11 – 如何从Surface创建位图(SharpDX)

我是DirectX的新手,并尝试使用SharpDX使用Desktop Duplication API捕获屏幕截图.

我想知道是否有任何简单的方法来创建我可以在CPU中使用的位图(即保存在文件等)

我使用以下代码获取桌面屏幕截图:

var factory = new SharpDX.DXGI.Factory1();
var adapter = factory.Adapters1[0];
var output = adapter.Outputs[0];

var device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                       DeviceCreationFlags.BgraSupport |
                                                       DeviceCreationFlags.Debug);

var dev1 = device.QueryInterface<SharpDX.DXGI.Device1>();

var output1 = output.QueryInterface<Output1>();
var duplication = output1.DuplicateOutput(dev1);
OutputDuplicateFrameInformation frameInfo;
SharpDX.DXGI.Resource desktopResource;
duplication.AcquireNextFrame(50, out frameInfo, out desktopResource);

var desktopSurface = desktopResource.QueryInterface<Surface>();

谁能告诉我如何从desktopSurface(DXGI.Surface实例)创建位图对象?

MSDN page for the Desktop Duplication API告诉我们图像的格式:

DXGI provides a surface that contains a current desktop image through the new IDXGIOutputDuplication::AcquireNextFrame method. The format of the desktop image is always DXGI_FORMAT_B8G8R8A8_UNORM no matter what the current display mode is.

您可以使用Surface.Map(MapFlags, out DataStream)方法访问CPU上的数据.

代码应该看起来像* this:

DataStream dataStream;
desktopSurface.Map(MapFlags.Read, out dataStream);
for(int y = 0; y < surface.Description.Width; y++) {
    for(int x = 0; x < surface.Description.Height; x++) {
        // read DXGI_FORMAT_B8G8R8A8_UNORM pixel:
        byte b = dataStream.Read<byte>();
        byte g = dataStream.Read<byte>();
        byte r = dataStream.Read<byte>();
        byte a = dataStream.Read<byte>();
        // color (r, g, b, a) and pixel position (x, y) are available
        // TODO: write to bitmap or process otherwise
    }
}
desktopSurface.Unmap();

*免责声明:我手边没有Windows 8安装,我只关注文档.我希望这有效:)

相关文章
相关标签/搜索