日期:2014-05-18  浏览次数:20799 次

关于BitmapData应用的疑惑。请大家帮忙
我要求某一图片的某一区域的灰度值。代码如下byte[,] rgbValue; //图像每一点的灰度值
C# code

Rectangle rect = myrect;//要处理的矩形区域
            if (bmpImg != null)//如果图片不为null。Bitmap bmpImg
            {
                System.Drawing.Imaging.BitmapData bmpData = bmpImg.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmpImg.PixelFormat);
                byte temp = 0;
                bmpHeight = rect.Height;
                bmpWidth = rect.Width;
                rgbValue = new byte[bmpHeight, bmpWidth];
                unsafe
                {
                    byte* ptr = (byte*)(bmpData.Scan0);
                    for (int i = 0; i < bmpHeight; i++)//高度
                    {
                        for (int j = 0; j < bmpWidth; j++)//宽度
                        {
                            temp = ptr[0];  //bgr排列
                            ptr += 1;
                            rgbValue[i, j] = temp;//当前选择的图像每一点的灰度值
                        }
/*重点是这里, 这句话我寻思了好久都没明白是什么意思。  求解. 明白是什么意思的朋友帮忙解释一下 哈~谢啦*/
                        ptr += bmpData.Stride - bmpWidth;
                    }
                }
                bmpImg.UnlockBits(bmpData);
            }



 分不多 麻烦了!!!

第二题:
我在msdn上看到了关于Bitmap..::.LockBits 方法的一个例子
[code=C#][/code]

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 = 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);

  // Set every third value to 255. A 24bpp bitmap will look red.  
  /*这里,为什么把每隔两个字节,把第三个字节赋值为255,图片看起来就偏红呢?*/
  for (int counter = 2; counter < rgbValues.Length; counter += 3)
  rgbValues[counter] = 255;

  // Copy the RGB values back to the bitmap
  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);

  }

还有请问各位 大侠们 我要学习这方面的知识 看哪本书比较好? 分不多 请多关照


------解决方案--------------------
灰度值表示的是亮度,数值越大像素的亮度越高,0的话就是个黑点,

探讨

还有一个重要问题忘记问了。。。
rgbValue[i, j] = temp;//当前选择的图像每一点的灰度值

这个灰度值越大颜色越黑 还是灰度值越小颜色越黑??
引用:

// Set every third value to 255. A 24bpp bitmap will look red.
/*这里,为什么把每隔两个字节,把第三个字节赋值为255,图片看起……