利用C#指針進(jìn)行圖像操作
由于C#指針操作屬于unsafe操作,所以很多人對unsafe使用起來都很謹(jǐn)慎
其實(shí)所謂不安全代碼,其實(shí)是不受控于CLR控制下的托管執(zhí)行,相當(dāng)于CLR領(lǐng)導(dǎo)下的部分區(qū)域自治,當(dāng)然CLR也不會(huì)去關(guān)心不安全代碼的內(nèi)存分配和回收
費(fèi)話少說,先體驗(yàn)一下適當(dāng)?shù)闹羔槻僮鲙淼男阅芴嵘?/P>
平時(shí)我們通過GDI+操作稍大點(diǎn)圖片象素時(shí),都會(huì)有一種瀕臨崩潰的感覺,我們轉(zhuǎn)下用指針操作。
1 Bitmap map = new Bitmap(path);
2 // 將圖片位圖區(qū)域進(jìn)行鎖定
3 BitmapData mapdata = map.LockBits(new Rectangle(0, 0, map.Width, map.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
4 unsafe
5 {
6 byte* pixpoint;
7 int newpoint;
8
9 for (int i = 0; i < map.Width; i++)
10 {
11 for (int j = 0; j < map.Height; j++)
12 {
13 // 位圖結(jié)構(gòu)存在一個(gè)字節(jié)對齊問題。
14 pixpoint = (byte*)mapdata.Scan0; +i * 3 + j * mapdata.Stride;
15 newpoint = (*pixpoint * 11 + *(pixpoint + 1) * 59 + *(pixpoint + 2) * 30) / 100;
16 *(pixpoint++) = (byte)newpoint;
17 *(pixpoint++) = (byte)newpoint;
18 *(pixpoint++) = (byte)newpoint;
19
20 // 非指針操作
21 // Color pxcl=map.GetPixel(i, j);
22 // map.SetPixel(i, j, (pxcl.R * 11 + pxcl.G * 59 + pxcl * 30) / 100);
23 }
24 }
25 }
26 // 將位圖內(nèi)存區(qū)域進(jìn)行解鎖
27 map.UnlockBits(mapdata);
28 map.Dispose();
比較GDI+使用的GetPixel/SetPixel,讓你立馬感到這個(gè)世界多么美妙
再來一個(gè)中值濾波的操作
10 byte s;
11 byte[] p = new byte[9];
12 int i, j;
13 int x, y;
14 int Stride;
15 unsafe
16 {
17 byte* point = (byte*)this.ImageData.Scan0;
18 Stride = this.ImageData.Stride;
19 point = point + 3 + this.ImageData.Stride;
20 for (i = 0; i < this.ImageData.Height - 1; i++)
21 {
22 for (j = 0; j < this.ImageData.Width - 1; j++)
23 {
24 p[0] = *(point - Stride - 1);
25 p[1] = *(point - Stride + 2);
26 p[2] = *(point - Stride + 5);
27 p[3] = *(point - 1);
28 p[4] = *(point + 2);
29 p[5] = *(point + 5);
30 p[6] = *(point + Stride - 1);
31 p[7] = *(point + Stride + 2);
32 p[8] = *(point + Stride + 5);
33 for (x = 0; x < 5; x++)
34 {
35 for (y = x + 1; y < 9; y++)
36 {
37 if (p[x] > p[y])
38 {
39 s = p[x];
40 p[x] = p[y];
41 p[y] = s;
42 }
43 }
44 }
45 *point = p[4];
46 *(point - 1) = p[4];
47 *(point - 2) = p[4];
48 point += 3;
49
50 }
51 point += Stride - this.ImageData.Width * 3;
52 }
53 }
54 }
55
【編輯推薦】