本函数完成的功能是对图像进行增亮处理,它比上面两个函数多了一个增亮参数-nBrightness,该参数由用户输入,范围为-255~255。在取得了增亮参数后,函数的unsafe代码部分对每个象素点的不同颜色成分进行逐个处理,即在原来值的基础上加上一个增亮参数以获得新的值。同时代码中还有一个防止成分值越界的操作,因为RGB成分值的范围为0~255,一旦超过了这个范围就要重新设置。函数最后执行成功后,同样得返回true值。
1 public static bool Brightness(Bitmap b, int nBrightness)
2 {
3 if (nBrightness < -255 || nBrightness > 255)
4 return false;
5 BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width,
6 b.Height), ImageLockMode.ReadWrite,
7 PixelFormat.Format24bppRgb);
8 int stride = bmData.Stride;
9 System.IntPtr Scan0 = bmData.Scan0;
10 int nVal = 0;
11 unsafe
12 {
13 byte * p = (byte *)(void *)Scan0;
14 int nOffset = stride - b.Width*3;
15 int nWidth = b.Width * 3;
16 for(int y=0;y<b.Height;++y)
17 {
18 for(int x=0; x < nWidth; ++x )
19 {
20 nVal = (int) (p[0] + nBrightness);
21 if (nVal < 0) nVal = 0;
22 if (nVal > 255) nVal = 255;
23 p[0] = (byte)nVal;
24 ++p;
25 }
26 p += nOffset;
27 }
28 }
29 b.UnlockBits(bmData);
30 return true;
31 }
2 {
3 if (nBrightness < -255 || nBrightness > 255)
4 return false;
5 BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width,
6 b.Height), ImageLockMode.ReadWrite,
7 PixelFormat.Format24bppRgb);
8 int stride = bmData.Stride;
9 System.IntPtr Scan0 = bmData.Scan0;
10 int nVal = 0;
11 unsafe
12 {
13 byte * p = (byte *)(void *)Scan0;
14 int nOffset = stride - b.Width*3;
15 int nWidth = b.Width * 3;
16 for(int y=0;y<b.Height;++y)
17 {
18 for(int x=0; x < nWidth; ++x )
19 {
20 nVal = (int) (p[0] + nBrightness);
21 if (nVal < 0) nVal = 0;
22 if (nVal > 255) nVal = 255;
23 p[0] = (byte)nVal;
24 ++p;
25 }
26 p += nOffset;
27 }
28 }
29 b.UnlockBits(bmData);
30 return true;
31 }