1. 程式人生 > >修改圖片為圓形

修改圖片為圓形

function createRoundImg($imgpath,$circle_path) {//$imgpath原圖片路徑,$circle_path完成後圖片儲存路徑
    $ext = pathinfo($imgpath);
    $src_img = null;
    switch ($ext['extension']) {
        case 'jpg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'png':
            $src_img = imagecreatefrompng($imgpath);
            break;
    }
    $wh = getimagesize($imgpath);
    $w  = $wh[0];
    $h  = $wh[1];
    $w = $h = min($w, $h);

    $image = imagecreatetruecolor($w, $h);
    $bg = imagecolorallocatealpha($image, 255, 255, 255, 127);
    imagesavealpha($image, true);
    imagefill($image, 0, 0, $bg);
    $r = $w / 2;
    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($image, $x, $y, $rgbColor);
            }
        }
    }
    header("content-type:image/png");
    imagepng($image,$circle_path);
    return $circle_path;
}