网站链接: 我爱捣鼓
当前位置: 首页 > web开发 > MVC

C#如何实现图片马赛克效果处理?

2021/3/4 21:55:08

我们经常会看到图片上面打上马赛克,一般人都会想到ps,如果通过C#程序如何实现了,可以看看下面的源码:using System.Drawing;using System.Drawing.Imaging;using System.Web.Mvc; namespace MVC2017_Sample.Controllers{ public class DefaultController : Control…

我们经常会看到图片上面打上马赛克,一般人都会想到ps,如果通过C#程序如何实现了,可以看看下面的源码:


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"> 影响范围 每一个格子数 </param>
        /// <returns></returns>
        public Bitmap AdjustTobMosaic(System.Drawing.Bitmap bitmap, int effectWidth)
        {
            // 差异最多的就是以照一定范围取样 玩之后直接去下一个范围
            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++;
                        }
                    }
 
                    // 计算范围平均
                    avgR = avgR / blurPixelCount;
                    avgG = avgG / blurPixelCount;
                    avgB = avgB / blurPixelCount;
 
                    // 所有范围内都设定此值
                    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;
        }
    }
}


相关资讯