Esempio n. 1
0
        public byte[] ExtractRawBitmap()
        {
            // use a cpu bound resource

            var textureDesc = new Texture2DDescription
            {
                MipLevels         = 1,
                ArraySize         = 1,
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                Format            = Format.B8G8R8A8_UNorm,
                OptionFlags       = ResourceOptionFlags.None,
                Width             = _width,
                Height            = _height,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SampleDescription(1, 0)
            };

            using (var cpuTexture = new Texture2D(_device, textureDesc))
            {
#if NETFX_CORE
                _device.ImmediateContext.CopyResource(_texture, cpuTexture);
#else
                _device.CopyResource(_texture, cpuTexture);
#endif
                var bytesPerLine = _width * 4;
                var res          = new byte[bytesPerLine * _height];
#if NETFX_CORE
                var data = _device.ImmediateContext.MapSubresource(cpuTexture, 0, MapMode.Read, MapFlags.None);
#else
                var data = cpuTexture.Map(0, MapMode.Read, MapFlags.None);
#endif
                try
                {
                    IntPtr sourcePtr    = data.DataPointer;
                    int    targetOffset = 0;
                    for (int i = 0; i != _height; ++i)
                    {
                        Marshal.Copy(sourcePtr, res, targetOffset, bytesPerLine);
#if NETFX_CORE
                        sourcePtr += data.RowPitch;
#else
                        sourcePtr += data.Pitch;
#endif
                        targetOffset += bytesPerLine;
                    }

                    return(res);
                }
                finally
                {
#if NETFX_CORE
                    _device.ImmediateContext.UnmapSubresource(cpuTexture, 0);
#else
                    cpuTexture.Unmap(0);
#endif
                }
            }
        }