PHP把圖片轉換成圓形png(頭像處理)
/*
* @fun 圖片轉換成圓形png,傳入源路徑和轉換後的路徑,均用相對於當前程序文件的路徑
* @memo 對於非正方形的圖片,以短邊作爲圖片的直徑
* @param string $src 源路徑
* @param string $dst 轉換後的路徑
* @return void
* @call z_image2circle("circleimage.jpg", './circleimage-'.uniqid().'.png');
*/
function z_image2circle($src, $dst){
//獲取原圖尺寸,並設置新圖片的寬度和高度
list($w, $h) = getimagesize($src);
if( $w > $h ){
$w = $h;
}else{
$h = $w;
}
$oimgSrc = imagecreatefromstring(file_get_contents($src));
$oimgDst = imagecreatetruecolor($w, $h);
imagealphablending($oimgDst,false);
$transparent = imagecolorallocatealpha($oimgDst, 0, 0, 0, 127);
$r=$w/2;
for($x=0;$x<$w;$x++){
for($y=0;$y<$h;$y++){
$c = imagecolorat($oimgSrc,$x,$y);
$_x = $x - $w/2;
$_y = $y - $h/2;
if((($_x*$_x) + ($_y*$_y)) < ($r*$r)){
imagesetpixel($oimgDst,$x,$y,$c);
}else{
imagesetpixel($oimgDst,$x,$y,$transparent);
}
}
}
imagesavealpha($oimgDst, true);
imagepng($oimgDst, $dst);
imagedestroy($oimgDst);
imagedestroy($oimgSrc);
}
//調用示例
z_image2circle('1.jpeg','circleimage-'.uniqid().'.png');
結果
生成以短邊爲直徑 的圓圖