imagecolorallocate()
是一個 PHP 圖像處理庫 GD 中的函數,用于為圖像分配顏色。要使用這個函數,首先確保已經安裝了 GD 庫。
以下是如何在 PHP 中使用 imagecolorallocate()
的示例:
<?php
// 創建圖像資源
$image = imagecreatetruecolor(200, 200);
// 為圖像分配顏色
$red = imagecolorallocate($image, 255, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);
$green = imagecolorallocate($image, 0, 255, 0);
// 在圖像上繪制矩形
imagefilledrectangle($image, 10, 10, 190, 190, $red);
imagefilledrectangle($image, 50, 50, 150, 150, $blue);
imagefilledrectangle($image, 90, 90, 110, 110, $green);
// 輸出圖像
header('Content-type: image/png');
imagepng($image);
// 銷毀圖像資源
imagedestroy($image);
?>
在這個示例中,我們首先使用 imagecreatetruecolor()
創建一個 200x200 的圖像資源。然后,我們使用 imagecolorallocate()
為圖像分配紅色、藍色和綠色。接下來,我們使用 imagefilledrectangle()
在圖像上繪制矩形,并使用 header()
和 imagepng()
輸出圖像。最后,我們使用 imagedestroy()
銷毀圖像資源。