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 DirectBitmap(int width, int height)
        {
            Width = width;
            Height = height;
            Bits = new int[width * height];
            BitsHandle = GCHandle.Alloc(Bits, GCHandleType.Pinned);
            Bitmap = new Bitmap(width, height, width * 4, PixelFormat.Format32bppPArgb, BitsHandle.AddrOfPinnedObject());
        }

        public void SetPixel(int x, int y, Color colour)
        {
            SetPixelRGB(x, y, colour.ToArgb());
        }

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

        public Color GetPixel(int x, int y)
        {
            return Color.FromArgb(GetPixelRGB(x, y));
        }

        public int GetPixelRGB(int 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 DirectBitmap(rc.Right - rc.Left, rc.Bottom - rc.Top);
            using (Graphics gp = Graphics.FromImage(image.Bitmap))
            {
                IntPtr dc = gp.GetHdc();
                FormHelper.PrintWindow(handle, dc, 0);
                gp.ReleaseHdc();
            }

 

转载于:https://www.cnblogs.com/xyz0835/p/9277582.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值