?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 = $rgb0xff;//取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);
}
}
}
}
}
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP圖形與圖片操作技巧匯總》、《PHP數組(Array)操作技巧大全》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP數學運算技巧總結》、《php字符串(string)用法總結》及《php常見數據庫操作技巧匯總》