PHP证件照换底色功能实现
本示例详细解析了利用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 '';
}
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程序设计的内容能对读者在相关领域的开发工作提供有益帮助。