【代码块】-图片-获取各像素点

发布时间 2023-08-08 23:16:29作者: 叫夏洛啊

整理代码块

代码块整理后存储,供后期使用

/*
这段代码是用于将图像的像素数据锁定、修改、然后再解锁的操作,以实现对图像像素的直接读写
*/

 private static byte[] LockUnlockBitsExample(Image img)
 {
     // Create a new bitmap. 
     Bitmap bmp = (Bitmap)img;

     // 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 = bmpData.Stride * bmp.Height;
     byte[] rgbValues = new byte[bytes];

     // Copy the RGB values into the array. 
     System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

     // Copy the RGB values back to the bitmap 
     System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

     // Unlock the bits. 
     bmp.UnlockBits(bmpData);

     return rgbValues;
 }