具體代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
using System.Drawing; using System.Drawing.Imaging; using System.Web.Mvc; namespace MVC2017_Sample.Controllers { public class DefaultController : Controller { public ActionResult Index() { //原圖 Image img = Image.FromFile( "c:\\1.jpg" ); Bitmap map = new Bitmap(img); //馬賽克處理后的圖片 Image img2 = AdjustTobMosaic(map, 20); img2.Save( "c:\\1_bak.jpg" , ImageFormat.Jpeg); return View(); } /// <summary> /// 馬賽克處理 /// </summary> /// <param name="bitmap"></param> /// <param name="effectWidth"> 影響范圍 每一個(gè)格子數(shù) </param> /// <returns></returns> public Bitmap AdjustTobMosaic(System.Drawing.Bitmap bitmap, int effectWidth) { // 差異最多的就是以照一定范圍取樣 玩之后直接去下一個(gè)范圍 for ( int heightOfffset = 0; heightOfffset < bitmap.Height; heightOfffset += effectWidth) { for ( int widthOffset = 0; widthOffset < bitmap.Width; widthOffset += effectWidth) { int avgR = 0, avgG = 0, avgB = 0; int blurPixelCount = 0; for ( int x = widthOffset; (x < widthOffset + effectWidth && x < bitmap.Width); x++) { for ( int y = heightOfffset; (y < heightOfffset + effectWidth && y < bitmap.Height); y++) { System.Drawing.Color pixel = bitmap.GetPixel(x, y); avgR += pixel.R; avgG += pixel.G; avgB += pixel.B; blurPixelCount++; } } // 計(jì)算范圍平均 avgR = avgR / blurPixelCount; avgG = avgG / blurPixelCount; avgB = avgB / blurPixelCount; // 所有范圍內(nèi)都設(shè)定此值 for ( int x = widthOffset; (x < widthOffset + effectWidth && x < bitmap.Width); x++) { for ( int y = heightOfffset; (y < heightOfffset + effectWidth && y < bitmap.Height); y++) { System.Drawing.Color newColor = System.Drawing.Color.FromArgb(avgR, avgG, avgB); bitmap.SetPixel(x, y, newColor); } } } } return bitmap; } } } |
總結(jié)
以上所述是小編給大家介紹的C#對(duì)圖片進(jìn)行馬賽克處理可控制模糊程度的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://blog.csdn.net/Andrewniu/article/details/80351508