php 图片局部打马赛克

来源:互联网 发布:任务清单统计系统 php 编辑:程序博客网 时间:2024/04/30 06:40

php 图片局部打马赛克


原理:

对图片中选定区域的每一像素,增加若干宽度及高度,生成矩型。而每一像素的矩型重叠在一起,就形成了马赛克效果。

本例使用GD库的imagecolorat获取像素颜色,使用imagefilledrectangle画矩型。


效果图:



代码如下:

[php] view plain copy
  1. <?php  
  2. /** 图片局部打马赛克 
  3. * @param  String  $source 原图 
  4. * @param  Stirng  $dest   生成的图片 
  5. * @param  int     $x1     起点横坐标 
  6. * @param  int     $y1     起点纵坐标 
  7. * @param  int     $x2     终点横坐标 
  8. * @param  int     $y2     终点纵坐标 
  9. * @param  int     $deep   深度,数字越大越模糊 
  10. * @return boolean 
  11. */  
  12. function imageMosaics($source$dest$x1$y1$x2$y2$deep){  
  13.   
  14.     // 判断原图是否存在  
  15.     if(!file_exists($source)){  
  16.         return false;  
  17.     }  
  18.   
  19.     // 获取原图信息  
  20.     list($owidth$oheight$otype) = getimagesize($source);  
  21.   
  22.     // 判断区域是否超出图片  
  23.     if($x1>$owidth || $x1<0 || $x2>$owidth || $x2<0 || $y1>$oheight || $y1<0 || $y2>$oheight || $y2<0){  
  24.         return false;  
  25.     }  
  26.   
  27.     switch($otype){  
  28.         case 1: $source_img = imagecreatefromgif($source); break;  
  29.         case 2: $source_img = imagecreatefromjpeg($source); break;  
  30.         case 3: $source_img = imagecreatefrompng($source); break;  
  31.         default:  
  32.             return false;  
  33.     }  
  34.   
  35.     // 打马赛克  
  36.     for($x=$x1$x<$x2$x=$x+$deep){  
  37.         for($y=$y1$y<$y2$y=$y+$deep){  
  38.             $color = imagecolorat($source_img$x+round($deep/2), $y+round($deep/2));  
  39.             imagefilledrectangle($source_img$x$y$x+$deep$y+$deep$color);  
  40.         }  
  41.     }  
  42.   
  43.     // 生成图片  
  44.     switch($otype){  
  45.         case 1: imagegif($source_img$dest); break;  
  46.         case 2: imagejpeg($source_img$dest); break;  
  47.         case 3: imagepng($source_img$dest); break;  
  48.     }  
  49.   
  50.     return is_file($dest)? true : false;  
  51.   
  52. }  
  53.   
  54. $source = 'source.jpg';  
  55. $dest = 'dest.jpg';  
  56.   
  57. $flag = imageMosaics($source$dest, 176, 98, 273, 197, 4);  
  58. echo '<img src="'.$source.'">';  
  59. echo '<img src="'.$dest.'">';  
  60.   
  61. ?> 
原创粉丝点击