C# Bitmap GetPixel 效率太低,太慢的替代方法

新建类 

    public class DirectBitmap : IDisposable
    {
        public Bitmap Bitmap { get; private set; }
        int[] Bits = null;
        public int Height { get; private set; }
        public int Width { get; private set; }

        protected GCHandle BitsHandle { get; private set; }

        public DirectBitmapint width, int height)
        {
            Width = width;
            Height = height;
            Bits = new int[width * height];
            BitsHandle = GCHandle.AllocBits, GCHandleType.Pinned);
            Bitmap = new Bitmapwidth, height, width * 4, PixelFormat.Format32bppPArgb, BitsHandle.AddrOfPinnedObject));
        }

        public void SetPixelint x, int y, Color colour)
        {
            SetPixelRGBx, y, colour.ToArgb));
        }

        public void SetPixelRGBint x, int y, int colour)
        {
            Bits[x + y * Width)] = colour;
        }

        public Color GetPixelint x, int y)
        {
            return Color.FromArgbGetPixelRGBx, y));
        }

        public int GetPixelRGBint x, int y)
        {
            return Bits[x + y * Width)];
        }

        private bool Disposed = false;

        public void Dispose)
        {
            if Disposed)
                return;
            Disposed = true;
            Bitmap.Dispose);
            BitsHandle.Free);
        }
    }

使用时:

声明DirectBitmap实例,访问DirectBitmap的Bitmap即可。 使用DirectBitmap的GetPixel方法来获取颜色 

            DirectBitmap image = new DirectBitmaprc.Right - rc.Left, rc.Bottom - rc.Top);
            using Graphics gp = Graphics.FromImageimage.Bitmap))
            {
                IntPtr dc = gp.GetHdc);
                FormHelper.PrintWindowhandle, dc, 0);
                gp.ReleaseHdc);
            }

Published by

风君子

独自遨游何稽首 揭天掀地慰生平