/// <summary>
        /// Initializes a new DirectXTexture class.
        /// </summary>
        /// <param name="bmp">The Bitmap.</param>
        internal DirectXTexture(System.Drawing.Bitmap bmp)
        {
            RawBitmap = (System.Drawing.Bitmap) bmp.Clone();
            _width = bmp.Width;
            _height = bmp.Height;
            var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height);
            var bitmapProperties = new BitmapProperties(
                new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96);
            var size = new Size2(bmp.Width, bmp.Height);

            int stride = bmp.Width*sizeof (int);
            using (var tempStream = new DataStream(bmp.Height*stride, true, true))
            {
                BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                for (int y = 0; y < bmp.Height; y++)
                {
                    int offset = bitmapData.Stride*y;
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        byte b = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte g = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte r = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte a = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = r | (g << 8) | (b << 16) | (a << 24);
                        tempStream.Write(rgba);
                    }
                }
                bmp.UnlockBits(bitmapData);
                tempStream.Position = 0;
                _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties);
            }
        }
Exemple #2
0
        public static Texture2D TextureFromBitmapThreadSafe(System.Drawing.Bitmap bmp)
        {
            int[] imgData = new int[bmp.Width * bmp.Height];
            Texture2D texture;
            texture = Texture2D.New(Engine.GraphicsContext.Device, bmp.Width, bmp.Height, PixelFormat.R8G8B8A8.UNorm);

            unsafe
            {
                // lock bitmap
                System.Drawing.Imaging.BitmapData origdata =
                    bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

                uint* byteData = (uint*)origdata.Scan0;

                // Switch bgra -> rgba
                for (int i = 0; i < imgData.Length; i++)
                {
                    byteData[i] = (byteData[i] & 0x000000ff) << 16 | (byteData[i] & 0x0000FF00) | (byteData[i] & 0x00FF0000) >> 16 | (byteData[i] & 0xFF000000);
                }

                // copy data
                System.Runtime.InteropServices.Marshal.Copy(origdata.Scan0, imgData, 0, bmp.Width * bmp.Height);

                byteData = null;

                // unlock bitmap
                bmp.UnlockBits(origdata);
            }

            // SetData uses the D3D11 Device Context which is not thread safe... execute
            // the SetData inside a critical section using the GraphicsDevice as the mutex
            Engine.GraphicsContext.ExclusiveDeviceExec(() => texture.SetData(imgData));

            return texture;
        }
Exemple #3
0
        public static Texture2D TextureFromBitmap(System.Drawing.Bitmap bmp)
        {
            int[] imgData = new int[bmp.Width * bmp.Height];
            Texture2D texture;
            texture = Texture2D.New(Engine.GraphicsContext.Device, bmp.Width, bmp.Height, PixelFormat.R8G8B8A8.UNorm);

            unsafe
            {
                // lock bitmap
                System.Drawing.Imaging.BitmapData origdata =
                    bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

                uint* byteData = (uint*)origdata.Scan0;

                // Switch bgra -> rgba
                for (int i = 0; i < imgData.Length; i++)
                {
                    byteData[i] = (byteData[i] & 0x000000ff) << 16 | (byteData[i] & 0x0000FF00) | (byteData[i] & 0x00FF0000) >> 16 | (byteData[i] & 0xFF000000);
                }

                // copy data
                System.Runtime.InteropServices.Marshal.Copy(origdata.Scan0, imgData, 0, bmp.Width * bmp.Height);

                byteData = null;

                // unlock bitmap
                bmp.UnlockBits(origdata);
            }

            texture.SetData(imgData);

            return texture;
        }
Exemple #4
0
        public static void ToBitmap(this InteropBitmap img, System.Drawing.Bitmap bmp)
        {
            if (img == null) return;
            int imgW = img.PixelWidth;
            int imgH = img.PixelHeight;
            byte[] byte_arr = new byte[(int)(4 * img.PixelWidth * img.PixelHeight)];

            int stride = ((img.PixelWidth * img.Format.BitsPerPixel + 31) & ~31) >> 3;
            img.CopyPixels(byte_arr, stride, 0);

            System.Drawing.Imaging.BitmapData bData;

            //The Width and Height should be static don't bother depending on the
            //InteropBitmap for them
            if (imgW == -1 || imgH == -1)
            {
                imgW = (int)img.PixelWidth;
                imgH = (int)img.PixelHeight;
            }

            bData = bmp.LockBits(new System.Drawing.Rectangle(new System.Drawing.Point(), bmp.Size),
                System.Drawing.Imaging.ImageLockMode.WriteOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            Marshal.Copy(byte_arr, 0, bData.Scan0, byte_arr.Length);
            bmp.UnlockBits(bData);
        }
        private SharpDX.Direct2D1.Bitmap SDXBitmapFromSysBitmap(WindowRenderTarget device, System.Drawing.Bitmap bitmap)
        {
            var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            var bitmapProperties = new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
            var size = new Size2(bitmap.Width, bitmap.Height);

            // Transform pixels from BGRA to RGBA
            int stride = bitmap.Width * sizeof(int);
            using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
            {
                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // Convert all pixels 
                for (int y = 0; y < bitmap.Height; y++)
                {
                    int offset = bitmapData.Stride * y;
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        // Not optimized 
                        byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = R | (G << 8) | (B << 16) | (A << 24);
                        tempStream.Write(rgba);
                    }

                }
                bitmap.UnlockBits(bitmapData);
                tempStream.Position = 0;

                return new SharpDX.Direct2D1.Bitmap(device, size, tempStream, stride, bitmapProperties);
            }
        }
        public static Texture2D TextureFromBitmap(Device device, System.Drawing.Bitmap bitmap)
        {
            BitmapData _BitmapData;
            _BitmapData = bitmap.LockBits(
                new DrawingRectangle(0, 0, bitmap.Width, bitmap.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb
            );

            var _TextureDescription = new Texture2DDescription {
                Width = bitmap.Width,
                Height = bitmap.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Usage = ResourceUsage.Immutable,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };
            _TextureDescription.SampleDescription.Count = 1;
            _TextureDescription.SampleDescription.Quality = 0;

            DataBox _Data;
            _Data.DataPointer = _BitmapData.Scan0;
            _Data.RowPitch = bitmap.Width * 4;
            _Data.SlicePitch = 0;

            var _Texture = new Texture2D(device, _TextureDescription, new[] { _Data });
            bitmap.UnlockBits(_BitmapData);

            return _Texture;
        }
Exemple #7
0
        public bool Initialise(System.Drawing.Bitmap bitmap)
        {
            RemoveAndDispose(ref _tex);
            RemoveAndDispose(ref _texSRV);

            //Debug.Assert(bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            System.Drawing.Imaging.BitmapData bmData;

            _texWidth = bitmap.Width;
            _texHeight = bitmap.Height;

            bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, _texWidth, _texHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            try
            {
                Texture2DDescription texDesc = new Texture2DDescription();
                texDesc.Width = _texWidth;
                texDesc.Height = _texHeight;
                texDesc.MipLevels = 1;
                texDesc.ArraySize = 1;
                texDesc.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                texDesc.SampleDescription.Count = 1;
                texDesc.SampleDescription.Quality = 0;
                texDesc.Usage = ResourceUsage.Immutable;
                texDesc.BindFlags = BindFlags.ShaderResource;
                texDesc.CpuAccessFlags = CpuAccessFlags.None;
                texDesc.OptionFlags = ResourceOptionFlags.None;

                SharpDX.DataBox data;
                data.DataPointer = bmData.Scan0;
                data.RowPitch = bmData.Stride;// _texWidth * 4;
                data.SlicePitch = 0;

                _tex = ToDispose(new Texture2D(_device, texDesc, new[] { data }));
                if (_tex == null)
                    return false;

                ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
                srvDesc.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                srvDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
                srvDesc.Texture2D.MipLevels = 1;
                srvDesc.Texture2D.MostDetailedMip = 0;

                _texSRV = ToDispose(new ShaderResourceView(_device, _tex, srvDesc));
                if (_texSRV == null)
                    return false;
            }
            finally
            {
                bitmap.UnlockBits(bmData);
            }

            _initialised = true;

            return true;
        }
        public static void CopyPixelsFromDrawingBitmap(System.Drawing.Bitmap source, int[] buffer)
        {
            System.Drawing.Imaging.BitmapData bitmapData = source.LockBits(
                new System.Drawing.Rectangle(0, 0, source.Width, source.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb
            );
            System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, buffer, 0, source.Width * source.Height);

            source.UnlockBits(bitmapData);
        }
Exemple #9
0
        private TextureHandle fromMemoryGDI(System.Drawing.Bitmap bmp)
        {
            var locked = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var texRet = new SlimDX.Direct3D9.Texture(mDevice, bmp.Width, bmp.Height, 1, SlimDX.Direct3D9.Usage.None, SlimDX.Direct3D9.Format.A8R8G8B8, SlimDX.Direct3D9.Pool.Managed);
            var surf = texRet.LockRectangle(0, SlimDX.Direct3D9.LockFlags.None);
            surf.Data.WriteRange(locked.Scan0, locked.Stride * locked.Height);
            texRet.UnlockRectangle(0);

            bmp.UnlockBits(locked);

            return new TextureHandle(texRet);
        }
Exemple #10
0
        private static byte[] BitmapToByteArray(System.Drawing.Bitmap bitmap)
        {
            System.Drawing.Imaging.BitmapData bmpdata = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
            int numbytes = bmpdata.Stride * bitmap.Height;
            byte[] bytedata = new byte[numbytes];
            IntPtr ptr = bmpdata.Scan0;

            Marshal.Copy(ptr, bytedata, 0, numbytes);

            bitmap.UnlockBits(bmpdata);

            return bytedata;
        }
        /// <summary>
        /// System.Drawing.ImageからSharpDX.Direct2D1.Bitmapを作成する
        /// </summary>
        /// <param name="renderTarget"></param>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static Bitmap LoadFromImage(RenderTarget renderTarget, string key, System.Drawing.Bitmap bitmap)
        {
            if (!ImageCash.ContainsKey(key))
            {
                var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);

                var imageint = new int[bitmap.Width * bitmap.Height];

                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly,
                                                 System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // Convert all pixels
                for (int y = 0; y < bitmap.Height; y++)
                {
                    int offset = bitmapData.Stride * y;
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        // Not optimized
                        byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = R | (G << 8) | (B << 16) | (A << 24);
                        imageint[bitmap.Width * y + x] = rgba;
                    }

                }
                bitmap.UnlockBits(bitmapData);
                ImageCash.Add(key, imageint);
            }

            // Transform pixels from BGRA to RGBA
            int stride = bitmap.Width * sizeof(int);
            using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
            {
                var bitmapProperties =
                    new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));

                var size = new Size2(bitmap.Width, bitmap.Height);

                var cash = ImageCash[key];

                foreach (var rgba in cash) { tempStream.Write(rgba); }

                tempStream.Position = 0;

                return new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties);
            }
        }
 public void Wykonaj(System.Drawing.Bitmap Bitmap, System.Collections.Generic.Stack<object> Argumenty)
 {
     Rectangle rect = new Rectangle(new Point(0,0), Bitmap.Size);
     BitmapData bd = Bitmap.LockBits(rect, ImageLockMode.ReadWrite, Bitmap.PixelFormat);
     int bytes = bd.Width * bd.Height * 3;
     byte[] rgbValues = new byte[bytes];
     System.Runtime.InteropServices.Marshal.Copy(bd.Scan0, rgbValues, 0, bytes);
     for (int i = 0; i < bytes; i++)
     {
         rgbValues[i] = (byte)((int)rgbValues[i] & 0x7f);
     }
     System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, bd.Scan0, bytes);
     Bitmap.UnlockBits(bd);
 }
Exemple #13
0
		/// <summary>
		/// Creates a prefab bitmap given a Ststem.Drawing.Bitmap
		/// </summary>
		public static Bitmap FromSystemDrawingBitmap(System.Drawing.Bitmap inputBitmap){

			int width = inputBitmap.Width;
			int height = inputBitmap.Height;
			int[] pixels = new int[width * height];

			BitmapData bitmapData = inputBitmap.LockBits(
				new Rectangle(0, 0, width, height),
				ImageLockMode.ReadOnly,
				System.Drawing.Imaging.PixelFormat.Format32bppArgb
			);
			System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, pixels, 0, pixels.Length);

			inputBitmap.UnlockBits(bitmapData);

			Bitmap toreturn = Bitmap.FromPixels (width, height, pixels);


			return toreturn;
		}
        public IplImage BitmapToIpImage(System.Drawing.Bitmap bitmapImg)
        {
            /*
             * 
             *  카메라로부터 받아온 비트맵 이미지를 OpenCV용 IplImage 화상으로 변환한다.
             * 
             * */

            IplImage retImage = Cv.CreateImage(new CvSize(bitmapImg.Width, bitmapImg.Height), BitDepth.U8, 3);

            System.Drawing.Imaging.BitmapData bmpData = bitmapImg.LockBits(
                                    new System.Drawing.Rectangle(0, 0, bitmapImg.Width, bitmapImg.Height),
                                    System.Drawing.Imaging.ImageLockMode.ReadWrite, 
                                    System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            //변환한 비트맵 데이터를 IplImage 스트림으로 옮긴다.
            CopyMemory(retImage.ImageData, bmpData.Scan0, bmpData.Stride * bmpData.Height);

            bitmapImg.UnlockBits(bmpData);

            return retImage;
        }
        public override System.Drawing.Bitmap DoAlgorithm(System.Drawing.Bitmap sourceImage)
        {
            //auteur: Jonathan Smit

            unsafe
            {
                //afbeelding vastzetten in geheugen
                BitmapData originalData = sourceImage.LockBits(
                    new Rectangle(0, 0, sourceImage.Width, sourceImage.Height),
                    ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

                //hoeveel bytes per pixel (voor jpg, 24-bit, is dat 24 gedeeld door 8 bit is 3 byte)
                int pixelSize = 3;

                //ipv 3x3 array gewoon een int-array van 3x3=9 waarden
                int[] pixels = new int[9];

                //voor n-keer 3x3: afbeelding hoogte en breedte - 2
                for (int y = 0; y < sourceImage.Height - 2; y++)
                {

                    //adres van de eerste pixel in elke rij van de afbeelding (scan0)
                    //adres van de eerste pixel in de rij
                    byte* oRow = (byte*)originalData.Scan0 + (y * originalData.Stride);
                    //voor het opslaan van de nieuwe gegevens beginnen we nog een rij lager
                    byte* nRow = (byte*)originalData.Scan0 + ((y + 1) * originalData.Stride);

                    int pixel;

                    for (int x = 0; x < sourceImage.Width - 2; x++)
                    {

                        //eerste rij
                        pixel = 0;
                        pixel = oRow[x * pixelSize];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 1];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 2];
                        pixels[0] = pixel;

                        pixel = 0;
                        pixel = oRow[x * pixelSize + 3];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 4];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 5];
                        pixels[1] = pixel;

                        pixel = 0;
                        pixel = oRow[x * pixelSize + 6];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 7];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 8];
                        pixels[2] = pixel;

                        //tweede rij
                        oRow = (byte*)originalData.Scan0 + ((y + 1) * originalData.Stride);

                        pixel = 0;
                        pixel = oRow[x * pixelSize];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 1];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 2];
                        pixels[3] = pixel;

                        pixel = 0;
                        pixel = oRow[x * pixelSize + 3];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 4];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 5];
                        pixels[4] = pixel;

                        pixel = 0;
                        pixel = oRow[x * pixelSize + 6];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 7];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 8];
                        pixels[5] = pixel;

                        //derde rij
                        oRow = (byte*)originalData.Scan0 + ((y + 2) * originalData.Stride);

                        pixel = 0;
                        pixel = oRow[x * pixelSize];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 1];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 2];
                        pixels[6] = pixel;

                        pixel = 0;
                        pixel = oRow[x * pixelSize + 3];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 4];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 5];
                        pixels[7] = pixel;

                        pixel = 0;
                        pixel = oRow[x * pixelSize + 6];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 7];
                        pixel = (pixel << 8) | oRow[x * pixelSize + 8];
                        pixels[8] = pixel;

                        //sorteer
                        Array.Sort(pixels);
                        //nieuwe pixel
                        pixel = pixels[4];

                        //nieuwe pixel ontleden en weer invoegen
                        nRow[x * pixelSize + 3] = (byte)(pixel & 0xFF);
                        nRow[x * pixelSize + 4] = (byte)((pixel >> 8) & 0xFF);
                        nRow[x * pixelSize + 5] = (byte)((pixel >> 16) & 0xFF);

                    }

                }

                //unlock the bitmaps
                sourceImage.UnlockBits(originalData);
                return sourceImage;
            }
        }
Exemple #16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bitmap"></param>
        public ManagedImage(System.Drawing.Bitmap bitmap)
        {
            Width = bitmap.Width;
            Height = bitmap.Height;

            int pixelCount = Width * Height;

            if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                Channels = ImageChannels.Alpha | ImageChannels.Color;
                Red = new byte[pixelCount];
                Green = new byte[pixelCount];
                Blue = new byte[pixelCount];
                Alpha = new byte[pixelCount];

                System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                unsafe
                {
                    byte* pixel = (byte*)bd.Scan0;

                    for (int i = 0; i < pixelCount; i++)
                    {
                        // GDI+ gives us BGRA and we need to turn that in to RGBA
                        Blue[i] = *(pixel++);
                        Green[i] = *(pixel++);
                        Red[i] = *(pixel++);
                        Alpha[i] = *(pixel++);
                    }
                }

                bitmap.UnlockBits(bd);
            }
            else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppGrayScale)
            {
                Channels = ImageChannels.Gray;
                Red = new byte[pixelCount];

                throw new NotImplementedException("16bpp grayscale image support is incomplete");
            }
            else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
            {
                Channels = ImageChannels.Color;
                Red = new byte[pixelCount];
                Green = new byte[pixelCount];
                Blue = new byte[pixelCount];

                System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
                        System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                unsafe
                {
                    byte* pixel = (byte*)bd.Scan0;

                    for (int i = 0; i < pixelCount; i++)
                    {
                        // GDI+ gives us BGR and we need to turn that in to RGB
                        Blue[i] = *(pixel++);
                        Green[i] = *(pixel++);
                        Red[i] = *(pixel++);
                    }
                }

                bitmap.UnlockBits(bd);
            }
            else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb)
            {
                Channels = ImageChannels.Color;
                Red = new byte[pixelCount];
                Green = new byte[pixelCount];
                Blue = new byte[pixelCount];

                System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
                        System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

                unsafe
                {
                    byte* pixel = (byte*)bd.Scan0;

                    for (int i = 0; i < pixelCount; i++)
                    {
                        // GDI+ gives us BGR and we need to turn that in to RGB
                        Blue[i] = *(pixel++);
                        Green[i] = *(pixel++);
                        Red[i] = *(pixel++);
                        pixel++;	// Skip over the empty byte where the Alpha info would normally be
                    }
                }

                bitmap.UnlockBits(bd);
            }
            else
            {
                throw new NotSupportedException("Unrecognized pixel format: " + bitmap.PixelFormat.ToString());
            }
        }
Exemple #17
0
        public static void UploadTexture(Texture tex, System.Drawing.Bitmap bitmap)
        {
            check(true);

            GL.Enable(EnableCap.Texture2D);
            GL.BindTexture(TextureTarget.Texture2D, tex.Pointer);

            lock (bitmap)
            {
                BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                // Actually upload the data.
                GL.TexImage2D(TextureTarget.Texture2D, 0, (int)PixelInternalFormat.Rgba8, bd.Width, bd.Height,
                              0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bd.Scan0);

                bitmap.UnlockBits(bd);
            }

            GL.Disable(EnableCap.Texture2D);
        }
Exemple #18
0
		// Add new frame to the AVI file
		public void AddFrame(System.Drawing.Bitmap bmp)
		{
			// check image dimension
			if ((bmp.Width != width) || (bmp.Height != height))
				throw new ApplicationException("Invalid image dimension");

			// lock bitmap data
			BitmapData	bmData = bmp.LockBits(
				new Rectangle(0, 0, width, height),
				ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

			// copy image data
			int srcStride = bmData.Stride;
			int dstStride = stride;

			//int src = bmData.Scan0.ToInt32() + srcStride * (height - 1);
			//int dst = buf.ToInt32();
			IntPtr dest = buf; 
			IntPtr src = IntPtr.Add(bmData.Scan0, srcStride * (height - 1));
			byte[] singleScanLine = new byte[srcStride]; 

			for (int y = 0; y < height; y++)
			{
				Marshal.Copy(src, singleScanLine, 0, srcStride);
				Marshal.Copy(singleScanLine, 0, dest, srcStride);
				// Win32.CopyMemory(dest, src, dstStride);

				dest = IntPtr.Add(dest, dstStride);
				src = IntPtr.Subtract(src, srcStride);
			}

			// unlock bitmap data
			bmp.UnlockBits(bmData);

			// write to stream
			if (Win32.AVIStreamWrite(streamCompressed, position, 1, buf, stride * height, 0, IntPtr.Zero, IntPtr.Zero) != 0)
			{ 
				throw new ApplicationException("Failed adding frame");
			}

			position++;
		}
Exemple #19
0
 private void DoInitialize(System.Drawing.Bitmap bitmap)
 {
     // generate texture.
     //  Lock the image bits (so that we can pass them to OGL).
     BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
         ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
     //GL.ActiveTexture(GL.GL_TEXTURE0);
     OpenGL.GetDelegateFor<OpenGL.glActiveTexture>()(OpenGL.GL_TEXTURE0);
     OpenGL.GenTextures(1, id);
     OpenGL.BindTexture(OpenGL.GL_TEXTURE_2D, id[0]);
     /* We require 1 byte alignment when uploading texture data */
     //GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
     /* Clamping to edges is important to prevent artifacts when scaling */
     OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_S, (int)OpenGL.GL_CLAMP_TO_EDGE);
     OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_T, (int)OpenGL.GL_CLAMP_TO_EDGE);
     /* Linear filtering usually looks best for text */
     OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, (int)OpenGL.GL_LINEAR);
     OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, (int)OpenGL.GL_LINEAR);
     OpenGL.TexImage2D(OpenGL.GL_TEXTURE_2D, 0, (int)OpenGL.GL_RGBA,
         bitmap.Width, bitmap.Height, 0, OpenGL.GL_BGRA, OpenGL.GL_UNSIGNED_BYTE,
         bitmapData.Scan0);
     //  Unlock the image.
     bitmap.UnlockBits(bitmapData);
     OpenGL.BindTexture(OpenGL.GL_TEXTURE_2D, 0);
 }
Exemple #20
0
        public static IntPtr CreatePixmapFromImage(Display display, System.Drawing.Bitmap image) 
        { 
            int width = image.Width;
            int height = image.Height;
            int size = width * height; 

            System.Drawing.Imaging.BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, width, height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            
            IntPtr ximage = XCreateImage(display, CopyFromParent, 24, ImageFormat.ZPixmap, 
                0, data.Scan0, (uint)width, (uint)height, 32, 0); 
            IntPtr pixmap = XCreatePixmap(display, XDefaultRootWindow(display), 
                width, height, 24); 
            IntPtr gc = XCreateGC(display, pixmap, IntPtr.Zero, null);
            
            XPutImage(display, pixmap, gc, ximage, 0, 0, 0, 0, (uint)width, (uint)height);
            
            XFreeGC(display, gc);
            image.UnlockBits(data);
                                         
            return pixmap; 
        } 
Exemple #21
0
        public System.Drawing.Bitmap ApplyOverlay(HeightData heights, System.Drawing.Bitmap overlayBitmap)
        {
            // prepare byte access to the overlay bitmap
            System.Drawing.Rectangle OverlayRect = new System.Drawing.Rectangle(0, 0, overlayBitmap.Width, overlayBitmap.Height);
            System.Drawing.Imaging.BitmapData overlayData = overlayBitmap.LockBits(OverlayRect, System.Drawing.Imaging.ImageLockMode.ReadOnly, overlayBitmap.PixelFormat);

            // create a blank bitmap and prepare it for byte access
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(heights.Width, heights.Height, overlayData.PixelFormat);
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, overlayBitmap.PixelFormat);

            // prepare memory space for the newly created color data
            byte[] bytes = new byte[data.Stride * bitmap.Height];
            byte[] overlayCopy = new byte[overlayData.Stride * overlayBitmap.Height];

            int pixelSize = overlayData.Stride / overlayBitmap.Width;

            // get a pointer to the to first line (=first pixel)
            IntPtr ptr = data.Scan0;
            IntPtr overlayPtr = overlayData.Scan0;

            // create a byte copy of the heightmap data
            System.Runtime.InteropServices.Marshal.Copy(overlayPtr, overlayCopy, 0, overlayData.Stride * overlayBitmap.Height);

            // create the color data

            // standard format overlay (positive values only)
            if (overlayBitmap.Width == 256)
            {
                for (int y = 0; y < heights.Height; y++)
                {
                    for (int x = 0; x < heights.Width; x++)
                    {
                        int index = y * data.Stride + x * pixelSize;

                        int current = (heights[x + y * heights.Width] / 128);

                        if (current < 0) current = 0;

                        // prevent water bleeding onto the coastline
                        if (heights[x + y * heights.Width] > 0 && current == 0) current = 1;

                        for (int channelIndex = 0; channelIndex < pixelSize; channelIndex++)
                        {
                            bytes[index + channelIndex] = overlayCopy[current * pixelSize + channelIndex];
                        }
                    }
                }
            }
            // extended overlay (positive AND negative values)
            else
            {
                for (int y = 0; y < heights.Height; y++)
                {
                    for(int x = 0; x < heights.Width; x++)
                    {
                        int index = y * data.Stride + x * pixelSize;

                        int current = 255 + (heights[x + y * heights.Width] / 128);

                        if (current < 0 || current > 511)
                        {
                            throw new Exception("This cannot happen");
                        }

                        // prevent water bleeding onto the coastline
                        if (current == 255 && heights[x + y * heights.Width] > 0) current = 256;
                     
                        for (int channelIndex = 0; channelIndex < pixelSize; channelIndex++)
                        {
                            bytes[index + channelIndex] = overlayCopy[current * pixelSize + channelIndex];
                        }
                    }
                }
            }

            // copy the data into the bitmap
            System.Runtime.InteropServices.Marshal.Copy(bytes, 0, ptr, data.Stride * bitmap.Height);

            // unlock the bits
            bitmap.UnlockBits(data);

            return bitmap;
        }
Exemple #22
0
		// Add new frame to the AVI file
		public void AddFrame(System.Drawing.Bitmap bmp)
		{
			// check image dimension
			if ((bmp.Width != width) || (bmp.Height != height))
				throw new ApplicationException("Invalid image dimension");

			// lock bitmap data
			BitmapData	bmData = bmp.LockBits(
				new Rectangle(0, 0, width, height),
				ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

			// copy image data
			int srcStride = bmData.Stride;
			int dstStride = stride;

			int src = bmData.Scan0.ToInt32() + srcStride * (height - 1);
			int dst = buf.ToInt32();

			for (int y = 0; y < height; y++)
			{
				Win32.memcpy(dst, src, dstStride);
				dst += dstStride;
				src -= srcStride;
			}

			// unlock bitmap data
			bmp.UnlockBits(bmData);

			// write to stream
			if (Win32.AVIStreamWrite(streamCompressed, position, 1, buf,
				stride * height, 0, IntPtr.Zero, IntPtr.Zero) != 0)
				throw new ApplicationException("Failed adding frame");

			position++;
		}
Exemple #23
0
        /// <summary>
        /// Apply shadow to mask onto the canvas
        /// </summary>
        /// <param name="clr">is the shadow color to be used</param>
        /// <param name="mask">is the mask image to be read</param>
        /// <param name="canvas">is the destination image to be draw upon</param>
        /// <param name="maskColor">is mask color used in mask image</param>
        /// <param name="offset">determine how much to offset the mask</param>
        /// <returns>true if successful</returns>
        public static bool ApplyShadowToMask(
            System.Drawing.Color clrShadow,
            System.Drawing.Bitmap mask,
            System.Drawing.Bitmap canvas,
            System.Drawing.Color maskColor,
            System.Drawing.Point offset)
        {
            if (mask == null || canvas == null)
                return false;

            BitmapData bitmapDataMask = new BitmapData();
            BitmapData bitmapDataCanvas = new BitmapData();
            Rectangle rectCanvas = new Rectangle(0, 0, canvas.Width, canvas.Height);
            Rectangle rectMask = new Rectangle(0, 0, mask.Width, mask.Height);

            mask.LockBits(
                rectMask,
                ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb,
                bitmapDataMask);

            canvas.LockBits(
                rectCanvas,
                ImageLockMode.WriteOnly,
                PixelFormat.Format32bppArgb,
                bitmapDataCanvas);

            unsafe
            {
                uint* pixelsMask = (uint*)bitmapDataMask.Scan0;
                uint* pixelsCanvas = (uint*)bitmapDataCanvas.Scan0;

                if (pixelsMask == null || pixelsCanvas == null)
                    return false;

                uint col = 0;
                int stride = bitmapDataCanvas.Stride >> 2;
                for (uint row = 0; row < bitmapDataCanvas.Height; ++row)
                {
                    for (col = 0; col < bitmapDataCanvas.Width; ++col)
                    {
                        if ((row - offset.Y) >= bitmapDataMask.Height || (col - offset.X) >= bitmapDataMask.Width ||
                            (row - offset.Y) < 0 || (col - offset.X) < 0)
                            continue;

                        uint index = (uint)(row * stride + col);
                        uint indexMask = (uint)((row - offset.Y) * (bitmapDataMask.Stride >> 2) + (col - offset.X));

                        byte maskByte = 0;

                        if (MaskColor.IsEqual(maskColor, MaskColor.Red))
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff0000) >> 16);
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Green))
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff00) >> 8);
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Blue))
                            maskByte = (Byte)(pixelsMask[indexMask] & 0xff);

                        uint color = (uint)(0xff << 24 | clrShadow.R << 16 | clrShadow.G << 8 | clrShadow.B);

                        if (maskByte > 0)
                        {
                            uint maskAlpha = (pixelsMask[indexMask] >> 24);
                            pixelsCanvas[index] = Alphablend(pixelsCanvas[index], color, (Byte)(maskAlpha), clrShadow.A);
                        }
                    }
                }
            }
            canvas.UnlockBits(bitmapDataCanvas);
            mask.UnlockBits(bitmapDataMask);

            return true;
        }
        internal static Bitmap ToSharpDXBitmap(RenderTarget rt, System.Drawing.Bitmap image, float symbolScale)
        {
            if (image == null)
                throw new ArgumentNullException("image");

            if (image.PixelFormat != GdiPixelFormat.Format32bppPArgb)
                return null;

            var imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly, image.PixelFormat);


            var dataStream = new DataStream(imageData.Scan0, imageData.Stride*imageData.Height, true, false);
            var properties = new BitmapProperties
            {
                PixelFormat = new SharpDX.Direct2D1.PixelFormat
                {
                    Format =   SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    AlphaMode = AlphaMode.Premultiplied
                }
            };

            // ToDo apply scaling here!
            //var scaler = new BitmapScaler(rt.Factory.NativePointer);
            //scaler.

            //Load the image from the gdi resource
            var result = new Bitmap(rt, new Size2(image.Width, image.Height), dataStream, imageData.Stride, properties);

            image.UnlockBits(imageData);

            return result;
        }
Exemple #25
0
        /// <summary>
        /// Apply image to mask onto the canvas
        /// </summary>
        /// <param name="image">is the image to be used</param>
        /// <param name="mask">is the mask image to be read</param>
        /// <param name="canvas">is the destination image to be draw upon</param>
        /// <param name="maskColor">is mask color used in mask image</param>
        /// <returns>true if successful</returns>
        public static bool ApplyImageToMask(
            System.Drawing.Bitmap image,
            System.Drawing.Bitmap mask,
            System.Drawing.Bitmap canvas,
            System.Drawing.Color maskColor,
            bool NoAlphaAtBoundary)
        {
            if (image == null || mask == null || canvas == null)
                return false;

            BitmapData bitmapDataImage = new BitmapData();
            BitmapData bitmapDataMask = new BitmapData();
            BitmapData bitmapDataCanvas = new BitmapData();
            Rectangle rectCanvas = new Rectangle(0, 0, canvas.Width, canvas.Height);
            Rectangle rectMask = new Rectangle(0, 0, mask.Width, mask.Height);
            Rectangle rectImage = new Rectangle(0, 0, image.Width, image.Height);

            image.LockBits(
                rectImage,
                ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb,
                bitmapDataImage);

            mask.LockBits(
                rectMask,
                ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb,
                bitmapDataMask);

            canvas.LockBits(
                rectCanvas,
                ImageLockMode.WriteOnly,
                PixelFormat.Format32bppArgb,
                bitmapDataCanvas);

            unsafe
            {
                uint* pixelsImage = (uint*)bitmapDataImage.Scan0;
                uint* pixelsMask = (uint*)bitmapDataMask.Scan0;
                uint* pixelsCanvas = (uint*)bitmapDataCanvas.Scan0;

                if (pixelsImage == null || pixelsMask == null || pixelsCanvas == null)
                    return false;

                uint col = 0;
                int stride = bitmapDataCanvas.Stride >> 2;
                for (uint row = 0; row < bitmapDataCanvas.Height; ++row)
                {
                    for (col = 0; col < bitmapDataCanvas.Width; ++col)
                    {
                        if (row >= bitmapDataImage.Height || col >= bitmapDataImage.Width)
                            continue;
                        if (row >= bitmapDataMask.Height || col >= bitmapDataMask.Width)
                            continue;

                        uint index = (uint)(row * stride + col);
                        uint indexMask = (uint)(row * (bitmapDataMask.Stride >> 2) + col);
                        uint indexImage = (uint)(row * (bitmapDataImage.Stride >> 2) + col);

                        byte maskByte = 0;

                        if (MaskColor.IsEqual(maskColor, MaskColor.Red))
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff0000) >> 16);
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Green))
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff00) >> 8);
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Blue))
                            maskByte = (Byte)(pixelsMask[indexMask] & 0xff);

                        if (maskByte > 0)
                        {
                            if (NoAlphaAtBoundary)
                            {
                                pixelsCanvas[index] = AlphablendNoAlphaAtBoundary(pixelsCanvas[index], pixelsImage[indexImage], (Byte)(pixelsMask[indexMask] >> 24), (Byte)(pixelsMask[indexMask] >> 24));
                            }
                            else
                            {
                                pixelsCanvas[index] = Alphablend(pixelsCanvas[index], pixelsImage[indexImage], (Byte)(pixelsMask[indexMask] >> 24), (Byte)(pixelsMask[indexMask] >> 24));
                            }
                        }
                    }
                }
            }
            canvas.UnlockBits(bitmapDataCanvas);
            mask.UnlockBits(bitmapDataMask);
            image.UnlockBits(bitmapDataImage);

            return true;
        }
Exemple #26
0
        /// <summary>
        /// System.Drawing.Bitmapから生成
        /// </summary>
        /// <param name="w">ウイジェット</param>
        /// <param name="bitmap">bitmap</param>
        /// <returns>XImageのインスタンス</returns>
        public static XImage FromBitmap(Widgets.IWidget w, System.Drawing.Bitmap bitmap)
        {
            var im = new XImage();

            var data = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                System.Drawing.Imaging.ImageLockMode.ReadWrite,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            int bytes = bitmap.Width * bitmap.Height * 4;
            byte[] buf = new byte[bytes];
            Marshal.Copy(data.Scan0, buf, 0, buf.Length);
            bitmap.UnlockBits(data);

            im.convertBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(byte)) * (buf.Length+1));
            Marshal.Copy(buf, 0, im.convertBuffer, buf.Length);

            im.image = NativeMethods.XCreateImage(w.NativeHandle.Display,
                0, 24, Format.ZPixmap, 0, im.convertBuffer, (uint)bitmap.Width, (uint)bitmap.Height, 32, 0);

            im.Width = bitmap.Width;
            im.Height = bitmap.Height;

            return im;
        }
Exemple #27
0
        /// <summary>
        /// Measure the mask image based on the mask color.
        /// </summary>
        /// <param name="mask">is the mask image to be measured</param>
        /// <param name="maskColor">is mask color used in mask image</param>
        /// <param name="top">returns the topmost Y </param>
        /// <param name="left">returns the leftmost X</param>
        /// <param name="bottom">returns the bottommost Y</param>
        /// <param name="right">returns the rightmost X</param>
        /// <returns>true if successful</returns>
        public static bool MeasureMaskLength(
            System.Drawing.Bitmap mask,
            System.Drawing.Color maskColor,
            ref uint top,
            ref uint left,
            ref uint bottom,
            ref uint right)
        {
            top = 30000;
            left = 30000;
            bottom = 0;
            right = 0;

            if (mask == null)
                return false;

            BitmapData bitmapDataMask = new BitmapData();
            Rectangle rect = new Rectangle(0, 0, mask.Width, mask.Height);

            mask.LockBits(
                rect,
                ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb,
                bitmapDataMask);

            unsafe
            {
                uint* pixelsMask = (uint*)bitmapDataMask.Scan0;

                if (pixelsMask == null)
                    return false;

                uint col = 0;
                int stride = bitmapDataMask.Stride >> 2;
                for (uint row = 0; row < bitmapDataMask.Height; ++row)
                {
                    for (col = 0; col < bitmapDataMask.Width; ++col)
                    {
                        uint index = (uint)(row * stride + col);
                        byte nAlpha = 0;

                        if (MaskColor.IsEqual(maskColor, MaskColor.Red))
                            nAlpha = (Byte)((pixelsMask[index] & 0xff0000) >> 16);
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Green))
                            nAlpha = (Byte)((pixelsMask[index] & 0xff00) >> 8);
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Blue))
                            nAlpha = (Byte)(pixelsMask[index] & 0xff);

                        if (nAlpha > 0)
                        {
                            if (col < left)
                                left = col;
                            if (row < top)
                                top = row;
                            if (col > right)
                                right = col;
                            if (row > bottom)
                                bottom = row;

                        }
                    }
                }
            }
            mask.UnlockBits(bitmapDataMask);

            return true;
        }
        public System.Drawing.Bitmap Process(System.Drawing.Bitmap original, bool normalize = true)
        {
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, original.Width, original.Height);
            System.Drawing.Imaging.BitmapData bmpData = original.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            IntPtr ptr = bmpData.Scan0;
            int bytes = Math.Abs(bmpData.Stride) * bmpData.Height;
            byte[] values = new byte[bytes];
            byte[] newValues = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes);

            _channelCount = values.Length / (bmpData.Width * bmpData.Height); // 3 либо 4 // UPD: теперь всегда 3
            try
            {
                // Дальше многа букафф, но я не смог придумать, как это записать более красиво без введения ещё кучи параметров
                if (!_separation)
                {
                    for (int y = 0; y < bmpData.Height; ++y)
                        for (int x = 0; x < bmpData.Width; ++x)
                        {
                            int index = GetIndex(x, y, bmpData.Width); // куды вставлять
                            double r = 0, g = 0, b = 0, sum = 0;
                            for (int j = -_matrix.Length / 2; j <= _matrix.Length / 2; ++j)
                                for (int i = -_matrix[0].Length / 2; i <= _matrix[0].Length / 2; ++i)
                                {
                                    // Идем по ядру. Если пиксель находится за пределами изображение, то я ничего не отражаю, не заворачиваю, а тупо игнорирую
                                    // Ну, не совсем тупо. Коэффициент нормировки пересчитывается на такой случай.
                                    // Вывод -- не нужно подавать на вход уже отнормированную руками матрицу. Не надо. Получится не совсем то :)
                                    // Т.е для box-фильтра нужно подать именно матрицу из единиц, а не из 1/9

                                    if ((x + i < 0) || (x + i >= bmpData.Width) || (y + j < 0) || (y + j >= bmpData.Height)) continue;
                                    int matrIndex = GetIndex(x + i, y + j, bmpData.Width); // влияющий сейчас пиксель
                                    double weight = _matrix[i + _matrix.Length / 2][j + _matrix.Length / 2];
                                    SumValues(values, ref sum, ref r, ref g, ref b, matrIndex, weight);
                                }
                            NormalizeValues(ref r, ref g, ref b, ref sum, normalize); // там нормировка
                            WriteNewValues(newValues, index, r, g, b);
                        }
                }
                else
                {
                    // сепарабельный фильтр
                    byte[] tmpValues = new byte[bytes];

                    // проход по строкам
                    for (int y = 0; y < bmpData.Height; ++y)
                    {
                        for (int x = 0; x < bmpData.Width; ++x)
                        {
                            int index = GetIndex(x, y, bmpData.Width);
                            double sum = 0, r = 0, g = 0, b = 0;
                            for (int k = -_matrix[0].Length / 2; k < _matrix[0].Length / 2; ++k) // здесь матрица суть вектор, инфа 100%
                            {
                                int i = x + k;
                                if ((i < 0) || (i >= bmpData.Width)) continue;
                                int matrIndex = GetIndex(i, y, bmpData.Width);
                                double weight = _matrix[0][k + _matrix[0].Length / 2];
                                SumValues(values, ref sum, ref r, ref g, ref b, matrIndex, weight);
                            }
                            NormalizeValues(ref r, ref g, ref b, ref sum, normalize);
                            WriteNewValues(tmpValues, index, r, g, b);
                        }
                    }

                    // проход по столбцам
                    for (int x = 0; x < bmpData.Width; ++x)
                        for (int y = 0; y < bmpData.Height; ++y)
                        {
                            int index = GetIndex(x, y, bmpData.Width);
                            double sum = 0, r = 0, g = 0, b = 0;
                            for (int k = -_matrix[0].Length / 2; k < _matrix[0].Length / 2; ++k)
                            {
                                int i = y + k;
                                if ((i < 0) || (i >= bmpData.Height)) continue;
                                int matrIndex = GetIndex(x, i, bmpData.Width);
                                double weight = _matrix[0][k + _matrix[0].Length / 2];
                                SumValues(tmpValues, ref sum, ref r, ref g, ref b, matrIndex, weight);
                            }
                            NormalizeValues(ref r, ref g, ref b, ref sum, normalize);
                            WriteNewValues(newValues, index, r, g, b);
                        }
                }
            }
            catch { }
            finally
            {
                System.Runtime.InteropServices.Marshal.Copy(newValues, 0, ptr, bytes);
                original.UnlockBits(bmpData);
            }
            return original;
        }
		/// <summary>
		/// Loads the bitmap by locking its bits.
		/// </summary>
		/// <param name="bitmap">
		/// A <see cref="Drawing.Bitmap"/> to be converted into an <see cref="Image"/> instance.
		/// </param>
		/// <param name='image'>
		/// A <see cref="Image"/> instance that will store <paramref name="bitmap"/> data.
		/// </param>
		/// <exception cref="ArgumentNullException">
		/// Exception thrown if <paramref name="bitmap"/> or <paramref name="image"/> is null.
		/// </exception>
		/// <exception cref="InvalidOperationException">
		/// Exception thrown if <paramref name="image"/> line stride is greater than <paramref name="bitmap"/> line
		/// stride. This never happens if <paramref name="image"/> is dimensionally compatible with <paramref name="bitmap"/>.
		/// </exception>
		private static void LoadBitmapByLockBits(System.Drawing.Bitmap bitmap, Image image)
		{
			if (bitmap == null)
				throw new ArgumentNullException("bitmap");
			if (image == null)
				throw new ArgumentNullException("image");

			System.Drawing.Imaging.BitmapData iBitmapData = null;
			IntPtr imageData = image.ImageBuffer;

			try {
				// Obtain source and destination data pointers
				iBitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);

				// Copy Bitmap data dst Image
				unsafe {
					byte* hImageDataPtr = (byte*)imageData.ToPointer();
					byte* iBitmapDataPtr = (byte*)iBitmapData.Scan0.ToPointer();
					uint hImageDataStride = image.Stride;
					uint iBitmapDataStride = (uint)iBitmapData.Stride;
					
					if (hImageDataStride > iBitmapDataStride)
						throw new InvalidOperationException("invalid bitmap stride");

					// .NET Image library stores bitmap scan line data in memory padded dst 4 bytes boundaries
					// .NET Image Library present a bottom up image, so invert the scan line order

					iBitmapDataPtr = iBitmapDataPtr + ((image.Height-1) * iBitmapDataStride);

					for (uint line = 0; line < image.Height; line++, hImageDataPtr += hImageDataStride, iBitmapDataPtr -= iBitmapDataStride)
						Memory.MemoryCopy(hImageDataPtr, iBitmapDataPtr, hImageDataStride);
				}
			} finally {
				if (iBitmapData != null)
					bitmap.UnlockBits(iBitmapData);
			}
		}
 private void updateImageDisplay(System.Drawing.Bitmap bmp)
 {
     Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
         new ThreadStart(delegate()
         {
             try
             {
                 if (SimulatorImage.Source != null && bmp != null)
                 {
                     //Console.WriteLine("updating image");
                     WriteableBitmap bmpsrc = SimulatorImage.Source as WriteableBitmap;
                     if (bmpsrc != null && bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                     {
                         //Console.WriteLine("copying");
                         int srcxoffset = (int)((bmp.Width - bmpsrc.Width) / 2);
                         int srcyoffset = (int)((bmp.Height - bmpsrc.Height) / 2);
                         int dstxoffset = 0;
                         int dstyoffset = 0;
                         if (srcxoffset < 0)
                         {
                             dstxoffset = -srcxoffset;
                             srcxoffset = 0;
                         }
                         if (srcyoffset < 0)
                         {
                             dstyoffset = -srcyoffset;
                             srcyoffset = 0;
                         }
                         int wid = Math.Min((int)bmpsrc.Width, bmp.Width + srcxoffset);
                         int hei = Math.Min((int)bmpsrc.Height, bmp.Height + srcyoffset);
                         var bmpdata = bmp.LockBits(
                             new System.Drawing.Rectangle(srcxoffset, srcyoffset, wid, hei),
                             System.Drawing.Imaging.ImageLockMode.ReadOnly,
                             bmp.PixelFormat);
                         bmpsrc.WritePixels(new Int32Rect(dstxoffset, dstyoffset, wid, hei),
                             bmpdata.Scan0,
                             bmpdata.Stride * bmpdata.Height,
                             bmpdata.Stride);
                         bmp.UnlockBits(bmpdata);
                         bmp.Dispose();
                     }
                 }
             }
             catch (Exception)
             { }
         }));
 }