将 .Net 位图转换为 SlimDx Texture2D 的工作速度非常快,如下所示: http ://www.rolandk.de/index.php?option=com_content&view=article&id=65:bitmap-from-texture-d3d11&catid=16:blog&Itemid=10
private Texture2D TextureFromBitmap(FastBitmapSingle fastBitmap)
{
Texture2D result = null;
DataStream dataStream = new DataStream(fastBitmap.BitmapData.Scan0, fastBitmap.BitmapData.Stride * fastBitmap.BitmapData.Height, true, false);
DataRectangle dataRectangle = new DataRectangle(fastBitmap.BitmapData.Stride, dataStream);
try
{
Texture2DDescription dt = new Texture2DDescription
{
BindFlags = BindFlags.ShaderResource,
CpuAccessFlags = CpuAccessFlags.None,
Format = Format.B8G8R8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
Usage = ResourceUsage.Immutable,
Width = fastBitmap.Size.X,
Height = fastBitmap.Size.Y,
ArraySize = 1,
SampleDescription = new SampleDescription(1, 0),
};
result = new Texture2D(device, dt, dataRectangle);
}
finally
{
dataStream.Dispose();
}
return result;
}
为了以正确的格式将纹理转换回.Net位图,我使用它,但它非常慢:
private bool BitmapFromTexture(FastBitmapSingle fastBitmap, Texture2D texture)
{
using (MemoryStream ms = new MemoryStream())
{
Texture2D.ToStream(device.ImmediateContext, texture, ImageFileFormat.Bmp, ms);
ms.Position = 0;
using (Bitmap temp1 = (Bitmap)Bitmap.FromStream(ms))
{
Rectangle bounds = new Rectangle(0, 0, temp1.Width, temp1.Height);
BitmapData BitmapDataIn = temp1.LockBits(bounds, ImageLockMode.ReadWrite, temp1.PixelFormat);
using (DataStream dataStreamIn = new DataStream(BitmapDataIn.Scan0, BitmapDataIn.Stride * BitmapDataIn.Height, true, false))
using (DataStream dataStreamOut = new DataStream(fastBitmap.BitmapData.Scan0, fastBitmap.BitmapData.Stride * fastBitmap.BitmapData.Height, false, true))
{
dataStreamIn.CopyTo(dataStreamOut);
}
temp1.UnlockBits(BitmapDataIn);
BitmapDataIn = null;
}
}
return true;
}
有没有更快的方法???我尝试了很多,例如:
但是 DataRectangle 的数据正好是我在 DataStream 中需要的数据的 8 倍:
private bool BitmapFromTexture(FastBitmapSingle fastBitmap, Texture2D texture)
{
using (Texture2D buff = Helper.CreateTexture2D(device, texture.Description.Width, texture.Description.Height, Format.B8G8R8A8_UNorm, BindFlags.None, ResourceUsage.Staging, CpuAccessFlags.Read | CpuAccessFlags.Write))
{
device.ImmediateContext.CopyResource(texture, buff);
using (Surface surface = buff.AsSurface())
using (DataStream dataStream = new DataStream(fastBitmap.BitmapData.Scan0, fastBitmap.BitmapData.Stride * fastBitmap.BitmapData.Height, false, true))
{
DataRectangle rect = surface.Map(SlimDX.DXGI.MapFlags.Read);
rect.Data.CopyTo(dataStream);
surface.Unmap();
}
}
return true;
}
有人可以帮忙吗?复制我的数据大约需要整个计算时间的 50%。如果这可以解决,我的应用程序会更快......