c# 指针方式操作图片

首先设置项目-属性-生成-去掉不允许安全代码

 

            //创建图像
            Bitmap image = new Bitmap(path);
            //获取图像的BitmapData对像
            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            //循环处理
            unsafe
            {
                byte* ptr = (byte*)(data.Scan0);
                byte bitsPerPixel = (byte)Image.GetPixelFormatSize(data.PixelFormat);
                for (int x = 0; x <data.Width; x++)
                {
                     for (int y = 0; y < data.Height ; ++y)
                    {
                        byte* pdata = ptr + y * data.Stride + x * bitsPerPixel / 8;

                       ///网上很多指针操作图片方式,但都是外层height里层width。无所谓哪个在外层,重点是上面这条语句,取到某行列交叉点的指针
                        ///然后用*(pdata) 、*(pdata + 1) 、*(pdata + 2)对应BGR,注意不是习惯性的RGB
                                              

                     }
                   
                }


              
            }
            Bitmap result = new Bitmap(image.Width, image.Height, data.Stride, PixelFormat.Format24bppRgb, data.Scan0);
           
            result.Save(dpath);

你可能感兴趣的:(c# 指针方式操作图片)