该函数中的BitmapData类型的bmData包含了图像文件的内部信息,bmData的Stride属性指明了一条线的宽度,而它的Scan0属性则是指向图像内部信息的指针。本函数完成的功能是图像颜色的翻转,实现的方法即用255减去图像中的每个象素点的值,并将所得值设置为原象素点处的值,对每个象素点进行如此的操作,只到整幅图像都处理完毕。函数中的unsafe代码块是整个函数的主体部分,首先我们取得图像内部数据的指针,然后设置好偏移量,同时设置nWidth为b.Width*3,因为每个象素点包含了三种颜色成分,对每个象素点进行处理时便要进行三次处理。接下来运用两个嵌套的for循环完成对每个象素点的处理,处理的核心便是一句:p[0] = (byte)(255-p[0]);。在unsafe代码块后,便可运用b.UnlockBits(bmData)进行图像资源的释放。函数执行成功,最后返回true值。
1
public static bool Invert(Bitmap b)
2
{
3
BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height),
4
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
5
int stride = bmData.Stride;
6
System.IntPtr Scan0 = bmData.Scan0;
7
unsafe
8
{
9
byte * p = (byte *)(void *)Scan0;
10
int nOffset = stride - b.Width*3;
11
int nWidth = b.Width * 3;
12
for(int y=0;y<b.Height;++y)
13
{
14
for(int x=0; x < nWidth; ++x )
15
{
16
p[0] = (byte)(255-p[0]);
17
++p;
18
}
19
p += nOffset;
20
}
21
}
22
b.UnlockBits(bmData);
23
return true;
24
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
