如何解决字节数组Sharpdx的Texture2d
我是C#,SharpDX和Directx新手。请原谅我的无知。我关注的是旧帖子:Exception of Texture2D.FromMemory() in SharpDX code。这非常有帮助。
我的目标:
- 从softwarebitmap构建Texture2d。
- 使纹理可用于HLSL。
我的处理方式:
- 使用IMemoryBufferByteAccess,我能够检索到字节的指针和Frame的总容量。从上一篇文章看来,我似乎需要使用DataRectangle指向字节数组。
- 具有2个具有不同描述符的纹理-Texture1(_staging_texture)-无绑定标志,cpu读写特权,使用阶段。我用指向字节数组的datarectangle创建了这个纹理。 Texture2(_final_texture)-着色器绑定标志,无cpu访问,用法-默认。最终将使该纹理可用于着色器。目的是使用从Texture1到Texture2的copyResource函数。
下面,我复制未修饰的代码以供参考:
bitmap = latestFrame.softwareBitmap;
Windows.Graphics.Imaging.BitmapBuffer bitmapBuffer= bitmap.LockBuffer(Windows.Graphics.Imaging.BitmapBufferAccessMode.Read);
Windows.Foundation.IMemoryBufferReference bufferReference = bitmapBuffer.CreateReference();
var staging_descriptor = new Texture2DDescription
{
Width = Width,Height = Height,MipLevels = 1,ArraySize = 1,Format = SharpDX.dxgi.Format.R8G8B8A8_Unorm,SampleDescription = new SharpDX.dxgi.SampleDescription(1,0),Usage = ResourceUsage.Staging,BindFlags = BindFlags.None,cpuAccessFlags = cpuAccessFlags.Read | cpuAccessFlags.Write,OptionFlags = ResourceOptionFlags.None
};
var final_descriptor = new Texture2DDescription
{
Width = Width,Usage = ResourceUsage.Default,BindFlags = BindFlags.ShaderResource,cpuAccessFlags = cpuAccessFlags.None,OptionFlags = ResourceOptionFlags.None
};
var dataRectangle = new SharpDX.DataRectangle();
unsafe
{
byte* dataInBytes;
uint capacityInBytes;
((InteropStatics.IMemoryBufferByteAccess)bufferReference).GetBuffer(out dataInBytes,out capacityInBytes);
dataRectangle.DataPointer = (IntPtr)dataInBytes;
dataRectangle.Pitch = 4;
}
Texture2D _stagingTexture = new Texture2D(device,staging_descriptor,dataRectangle);
Texture2D _finalTexture = new Texture2D(device,final_descriptor);
_stagingTexture.Device.ImmediateContext.copyResource(_stagingTexture,_finalTexture);
我的问题有两个:
- 当从以下位置检索指针时,DataRectangle使用IntPtr类型 接口是字节数组。这不是问题吗?或者 在DataRectangle中的成员是否解决了这个问题?现在我投了 从byteArray到IntPtr。
- 这种方法行得通吗?还是有更好的方法来解决这个问题?
任何指针,建议或建设性的批评将不胜感激!
解决方法
前一段时间,我一直在寻找相同的功能,但是我想出了这个功能,该功能在我的用例中总是可以正常工作
public static Texture2D CreateTexture2DFrombytes(Device device,byte[] RawData,int width,int height)
{
Texture2DDescription desc;
desc.Width = width;
desc.Height = height;
desc.ArraySize = 1;
desc.BindFlags = BindFlags.ShaderResource;
desc.Usage = ResourceUsage.Immutable;
desc.CpuAccessFlags = CpuAccessFlags.None;
desc.Format = Format.B8G8R8A8_UNorm;
desc.MipLevels = 1;
desc.OptionFlags = ResourceOptionFlags.None;
desc.SampleDescription.Count = 1;
desc.SampleDescription.Quality = 0;
DataStream s = DataStream.Create(RawData,true,true);
DataRectangle rect = new DataRectangle(s.DataPointer,width * 4);
Texture2D t2D = new Texture2D(device,desc,rect);
return t2D;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。