PHP 畫出 透明背景 的 圓形 圖片程式

PHP 想要用 GD 來畫出圓形、橢圓形等等的圖形,該怎麼畫呢?背景想要是透明的,要怎麼做呢?

PHP 畫出 透明背景 的 圓形 圖片程式

這邊來示範下述:

  1. 圖片畫出 圓形 和 橢圓形
  2. 畫兩個不同的圓形

這些圖片的背景,全部都設定為透明。(因為要透明背景,所以範例都使用 png)

下述會用到幾個主要的 Function:

  • imagecolorallocate() - Allocate a color for an image (指定圖片一個顏色)
  • imagefilledellipse() - Draw a filled ellipse (畫一個填滿的橢圓形)
    • imagefilledellipse($im, x位置, y位置, 寬, 高, imagecolorallocate(指定的顏色))
    • 寬、高若一致,就會畫出圓形,減少則會變成橢圓形
  • imagecolortransparent() - Define a color as transparent (指定某個顏色為透明)
    • imagecolortransparent($im, imagecolorallocate(指定的顏色));
    • 將某個顏色設定為透明背景 (任何顏色都可以指定為透明背景,不用特定顏色)

圖片畫出 圓形 和 橢圓形 (透明背景)

<?php
header("Content-type:image/png");

$im = imagecreatetruecolor(200, 200); // 建立空的圖片

$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $white); // 填滿白色 (背景)
imagefilledellipse($im, 100, 100, 200, 200, $black);
// imagefilledellipse($im, 100, 100, 200, 100, $black); // 改成此行則畫出 橢圓形

imagecolortransparent($im, $white); // 將白色設定為透明背景

imagepng($im);
imagedestroy($im);
?>

畫兩個不同的圓形 (橫排 + 透明背景)

<?php
header("Content-type:image/png");

$im = imagecreatetruecolor(400, 200);

$yellow = imagecolorallocate($im, 255, 255, 0);
$black  = imagecolorallocate($im, 0, 0, 0);
$red    = imagecolorallocate($im, 255,0,0);

imagefill($im, 0, 0, $yellow);
imagefilledellipse($im, 100, 100, 200, 200, $black);
imagefilledellipse($im, 300, 100, 200, 200, $red);

imagecolortransparent($im, $yellow); // 將黃色設定為透明背景

imagepng($im);
imagedestroy($im);
?>

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料