Example #1
0
        /// <summary>
        /// Converts a <see cref="System.Drawing.Bitmap"/> object into a <see cref="SharpDX.Direct2D1.Bitmap"/> object for rendering.
        /// </summary>
        /// <param name="renderTarget">The <see cref="SharpDX.Direct2D1.RenderTarget"/> object that images are drawn on.</param>
        /// <param name="bmp">The .NET native bitmap image.</param>
        /// <returns>A <see cref="SharpDX.Direct2D1.Bitmap"/> containing the image data retrieved from the <see cref="System.Drawing.Bitmap"/> object.</returns>
        public static Bitmap FromSysBMP(RenderTarget renderTarget, SystemBitmap bmp)
        {
            var imageArea = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
            var bmpProps = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));

            // Unmanaged buffer needs proper disposal
            using (var dataStream = new DataStream(bmp.ByteSize(), true, true))
            {
                var bmpData = bmp.LockBits(imageArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                for (int y = 0; y < bmp.Height; y++)
                {
                    int offset = y * bmpData.Stride;
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        // System bitmaps store pixel values as BGRA byte arrays
                        byte b = Marshal.ReadByte(bmpData.Scan0, offset++);
                        byte g = Marshal.ReadByte(bmpData.Scan0, offset++);
                        byte r = Marshal.ReadByte(bmpData.Scan0, offset++);
                        byte a = Marshal.ReadByte(bmpData.Scan0, offset++);

                        // Convert BGRA to RGBA (stored as a 32 bit = 4 byte integer)
                        int rgba = r | (g << 8) | (b << 16) | (a << 24);

                        // Write the RGBA value to the data buffer
                        dataStream.Write(rgba);
                    }
                }

                // Release the lock on the bitmap & reset the buffer position pointer
                bmp.UnlockBits(bmpData);
                dataStream.Position = 0;

                return new Bitmap(renderTarget, new Size2(bmp.Width, bmp.Height), dataStream, bmpData.Stride, bmpProps);
            }
        }