110,535
社区成员
发帖
与我相关
我的任务
分享
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);
}
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
tmp = bmp.GetPixel(x, y);
}
}