php正方形圖片轉成成圓形圖片-GD
阿新 • • 發佈:2021-10-29
/** * 剪下圖片為圓形 * @param $picture 圖片資料流 比如file_get_contents(imageurl)返回的東東 * @return 圖片資料流 */ private function circular_image($picture) { $src_img = imagecreatefromstring($picture); $w = imagesx($src_img); $h = imagesy($src_img); $w = min($w, $h); $h = $w; $img = imagecreatetruecolor($w, $h); //這一句一定要有 imagesavealpha($img, true); //拾取一個完全透明的顏色,最後一個引數127為全透明 $bg = imagecolorallocatealpha($img, 0, 0, 0, 127); imagefill($img, 0, 0, $bg); $r = $w / 2; // 圓半徑 $y_x = $r; // 圓心X座標 $y_y = $r; // 圓心Y座標 for ($x = 0; $x < $w; $x++) { for ($y = 0; $y < $h; $y++) { $rgbColor = imagecolorat($src_img, $x, $y); if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) { imagesetpixel($img, $x, $y, $rgbColor); } } } /** * 如果想要直接輸出圖片,應該先設header。header("Content-Type: image/png; charset=utf-8"); * 並且去掉快取區函式 */ //獲取輸出快取,否則imagepng會把圖片輸出到瀏覽器 ob_start(); imagepng ( $img ); imagedestroy($img); $contents = ob_get_contents(); ob_end_clean(); return $contents; }