使用asp.net改变图片颜色

最近奇葩经理提出了奇葩的需求,要能在网站上改变图片的颜色,比如灰色的变成彩色,彩色的变成灰色,尼玛楼主的感受你们不懂!于是有了下面的代码。。。

用法:调用update_pixelColor方法并传参数即可 

C#代码  收藏代码
  1. #region 改变图片颜色  
  2.   
  3. /// <summary>  
  4. /// 改变图片的颜色  
  5. /// </summary>  
  6. /// <param name="filePath">图片的完整路径</param>  
  7. /// <param name="colorIndex">改变的颜色,true为灰色,false为彩色</param>  
  8. public void update_pixelColor(string filePath, bool colorIndex)  
  9. {  
  10.     Bitmap bmp = new Bitmap(Bitmap.FromFile(filePath));  
  11.   
  12.     int value = 0;  
  13.   
  14.     for (int i = 0; i < bmp.Height; i++)  
  15.     {  
  16.         for (int j = 0; j < bmp.Width; j++)  
  17.         {  
  18.             if (colorIndex)  
  19.                 value = this.GetGrayNumColor(bmp.GetPixel(j, i));  
  20.             else  
  21.                 value = this.GetHongNumColor(bmp.GetPixel(j, i));  
  22.   
  23.             bmp.SetPixel(j, i, Color.FromArgb(value, value, value));  
  24.         }  
  25.     }  
  26.   
  27.     bmp.Save(filePath);  
  28. }  
  29.   
  30. /// <summary>  
  31. /// 获取彩色单点像素  
  32. /// </summary>  
  33. /// <param name="posClr">单点像素</param>  
  34. /// <returns>int</returns>  
  35. private int GetHongNumColor(Color posClr)  
  36. {  
  37.     return (posClr.R * 19595 + posClr.G * 38469 + posClr.B * 7472) >> 16;  
  38. }  
  39.   
  40. /// <summary>  
  41. /// 获取灰色单点像素  
  42. /// </summary>  
  43. /// <param name="posClr">单点像素</param>  
  44. /// <returns>Color</returns>  
  45. private int GetGrayNumColor(Color posClr)  
  46. {  
  47.     //要改变ARGB  
  48.     return (posClr.R * 19595 + posClr.G * 38469 + posClr.B * 7472) >> 16;  
  49. }  
  50.  
  51. #endregion 改变图片颜色  


这个转换的比较慢 看到编程人生上有关于这方面的总结,哪天来研究一下

posted @ 2014-08-11 17:16  Ranran  阅读(742)  评论(1编辑  收藏  举报