[C#]快速读写Bitmap像素

来源:互联网 发布:阿里在线编程测验作弊 编辑:程序博客网 时间:2024/06/06 03:01

原文作者:conmajia
原文链接:http://topic.csdn.net/u/20120710/12/A6326F1D-D329-4268-9A04-76CFED772612.html

使用Bitmap类时经常会用到GetPixel和SetPixel,但是这两个方法直接使用都比较慢,所以一般都会使用LockBits/UnlockBits将位图在内存中锁定,以加快操作速度。

private void LockUnlockBitsExample(PaintEventArgs e)        {            // Create a new bitmap.创建位图            Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");            // Lock the bitmap's bits.  锁定位图            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);            System.Drawing.Imaging.BitmapData bmpData =                bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,                bmp.PixelFormat);            // Get the address of the first line.获取首行地址            IntPtr ptr = bmpData.Scan0;            // Declare an array to hold the bytes of the bitmap.定义数组保存位图            int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;            byte[] rgbValues = new byte[bytes];            // Copy the RGB values into the array.复制RGB值到数组            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);            // Set every third value to 255. A 24bpp bitmap will look red.  把每像素第3个值设为255.24bpp的位图将变红            for (int counter = 2; counter < rgbValues.Length; counter += 3)                rgbValues[counter] = 255;            // Copy the RGB values back to the bitmap 把RGB值拷回位图            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);            // Unlock the bits.解锁            bmp.UnlockBits(bmpData);            // Draw the modified image.绘制更新了的位图            e.Graphics.DrawImage(bmp, 0, 150);        }


原创粉丝点击