当前位置: 移动技术网 > IT编程>开发语言>c# > C#对图片进行马赛克处理可控制模糊程度的实现代码

C#对图片进行马赛克处理可控制模糊程度的实现代码

2019年07月18日  | 移动技术网IT编程  | 我要评论

具体代码如下所示:

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;
  }
 }
} 

总结

以上所述是小编给大家介绍的c#对图片进行马赛克处理可控制模糊程度的实现代码,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网