您的位置:首页技术文章
文章详情页

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

【字号: 日期:2022-09-10 09:58:52浏览:52作者:猪猪

本文实例讲述了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='https://www.haobala.com/bcjs/’.$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相关内容感兴趣的读者可查看本站专题:《PHP图形与图片操作技巧汇总》、《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《PHP数学运算技巧总结》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

标签: PHP
相关文章: