当前位置:首页 > 后端 > php > php实现的证件照换底色功能示例【人像抠图/换背景图】

php实现的证件照换底色功能示例【人像抠图/换背景图】

DChen3年前 (2021-06-20)php2.67 K0

本文实例讲述了php实现的证件照换底色功能。分享给大家供大家参考,具体如下:

<?PHP
//背景图和原图需要保持宽高要保持一样,这里的示例原图用的是蓝色背景
init();
function init(){
  $old = '1.png';
  $new = '2.png';
  //创建一个png透明图
  $img = imagecreatefrompng($old);
  setpng($img,$old,$new);
}
function setpng($imgid,$filename,$savename){
  $bg = 'bg.png';//背景图
  $new = imagecreatefrompng($bg);//创建一个png透明图
  list($width,$height)=getimagesize($filename);//获取长和宽
  $white = imagecolorallocate($imgid,1,155,215);//选择一个替换颜色。这里是绿色
  cleancolor($imgid,$white);
  imagecolortransparent($imgid,$white);//把选择的颜色替换成透明
  imagecopymerge($new,$imgid,0,0,0,0,$width,$height,100);//合并图片
  imagepng($new,$savename);//保存图片
  imagedestroy($imgid);//销毁
  imagedestroy($new);
  echo '<img src="'.$savename.'">';
}
function cleancolor($imgid,$color){
  $width = imagesx($imgid);//获取宽
  $height = imagesy($imgid);//获取高
  for($i=0;$i<$width;$i++){
    for($k=0;$k<$height;$k++){
      //对比每一个像素
      $rgb = imagecolorat($imgid,$i,$k);
      $r = ($rgb >> 16)&0xff;//取R
      $g = ($rgb >> 8)&0xff;//取G
      $b = $rgb&0xff;//取B
      $randr = 1.5;
      $randg = 1;
      $randb=1;
      //蓝色RGB大致的位置。替换成绿色
      if($r<=65*$randr && $g<=225*$randg && $b<=255*$randb && $b*$randb>=100){
        //如果能够精确的计算出要保留位置的,这里可以写绝对的数字
        if($i>=$width/2 && $i<=$width/2 && $k>=$height/2 && $k<=$height/2){
          
        }else{
          //改变颜色
          imagesetpixel($imgid,$i,$k,$color);
        }
      }
    }
  }
}
  • $old指的是要处理的图片,指定为png格式

  • $new指的是处理后输出的图片名

  • $bg指的是背景图

php实现的证件照换底色功能示例【人像抠图/换背景图】  php 抠图 第1张



取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

版权声明:本文由“憨小猪”发布,如需转载请注明出处。

本文链接:https://www.phper.red/post/124.html

标签: php抠图

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。