gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:14:40 26 4
gpt4 key购买 nike

我是 DirectX 的新手,并尝试使用 SharpDX 使用桌面复制 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 实例)创建位图对象的想法?

最佳答案

我自己刚刚完成了这个,虽然我不会对这段代码多说!

public byte[] GetScreenData()
{
// We want to copy the texture from the back buffer so
// we don't hog it.
Texture2DDescription desc = BackBuffer.Description;
desc.CpuAccessFlags = CpuAccessFlags.Read;
desc.Usage = ResourceUsage.Staging;
desc.OptionFlags = ResourceOptionFlags.None;
desc.BindFlags = BindFlags.None;

byte[] data = null;

using (var texture = new Texture2D(DeviceDirect3D, desc))
{
DeviceContextDirect3D.CopyResource(BackBuffer, texture);

using (Surface surface = texture.QueryInterface<Surface>())
{
DataStream dataStream;
var map = surface.Map(SharpDX.DXGI.MapFlags.Read, out dataStream);
int lines = (int)(dataStream.Length / map.Pitch);
data = new byte[surface.Description.Width * surface.Description.Height * 4];

int dataCounter = 0;
// width of the surface - 4 bytes per pixel.
int actualWidth = surface.Description.Width * 4;
for (int y = 0; y < lines; y++)
{
for (int x = 0; x < map.Pitch; x++)
{
if (x < actualWidth)
{
data[dataCounter++] = dataStream.Read<byte>();
}
else
{
dataStream.Read<byte>();
}
}
}
dataStream.Dispose();
surface.Unmap();
}
}

return data;
}

这将为您提供一个 byte[],然后可以使用它来生成位图。

以下是我如何保存到 png 图像。
 using (var stream = await file.OpenAsync( Windows.Storage.FileAccessMode.ReadWrite ))
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
double dpi = DisplayProperties.LogicalDpi;

encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
(uint)width, (uint)height, dpi, dpi, pixelData);
encoder.BitmapTransform.ScaledWidth = (uint)newWidth;
encoder.BitmapTransform.ScaledHeight = (uint)newHeight;
await encoder.FlushAsync();
waiter.Set();
}

我知道这是不久前回答的,也许你现在已经明白了:3 但如果其他人被卡住了,我希望这会有所帮助!

关于directx-11 - 如何从 Surface (SharpDX) 创建位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16020988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com