在PHP 中,圖像處理功能由GD 庫提供, imagecreatetruecolor()和imageopenpolygon()是其中非常有用的兩個函數。本文將為您展示如何使用這兩個函數從零開始創建圖像並繪製一個簡單的多邊形。我們將一步步介紹如何創建圖像,設置圖像顏色,並使用多邊形方法將圖形呈現出來。
imagecreatetruecolor()是一個非常基礎的函數,用於創建一個真彩色圖像資源。它接收兩個參數:圖像的寬度和高度,返回一個表示圖像的資源。
<?php
// 創建一個寬 500 高 500 的圖像
$width = 500;
$height = 500;
$image = imagecreatetruecolor($width, $height);
這個函數返回的$image變量就是圖像的資源,接下來你可以用它來進行圖像處理操作。
在圖像中,我們通常需要設置不同的顏色來繪製形狀、背景等。可以使用imagecolorallocate()來分配顏色。它接受4 個參數:圖像資源、紅色、綠色和藍色的值(0-255)。
// 分配背景色和多邊形顏色
$background_color = imagecolorallocate($image, 255, 255, 255); // 白色背景
$polygon_color = imagecolorallocate($image, 0, 0, 255); // 藍色多邊形
使用imagefill()可以將整個圖像填充為指定的顏色。例如,在我們創建圖像後,我們要填充一個白色背景。
// 填充背景色
imagefill($image, 0, 0, $background_color);
接下來,我們使用imagepolygon()繪製一個多邊形。該函數的參數包括圖像資源、頂點坐標數組和頂點數。多邊形的每個頂點由一個坐標(x, y)來表示。
// 多邊形的頂點坐標
$points = array(
150, 150,
350, 150,
400, 350,
200, 400,
100, 300
);
// 繪製多邊形
imagepolygon($image, $points, 5, $polygon_color);
最後,我們需要輸出創建的圖像。 PHP 提供了imagepng() 、 imagejpeg()和imagegif()等函數,您可以根據需要選擇其中一種來輸出圖像。在此,我們使用imagepng()將圖像保存為PNG 格式。
// 輸出圖像到瀏覽器
header('Content-Type: image/png');
imagepng($image);
// 或者保存為文件
// imagepng($image, 'polygon_image.png');
一旦圖像生成完畢,為了節省內存,應該釋放圖像資源。
// 銷毀圖像資源
imagedestroy($image);
<?php
// 創建圖像資源
$width = 500;
$height = 500;
$image = imagecreatetruecolor($width, $height);
// 分配顏色
$background_color = imagecolorallocate($image, 255, 255, 255); // 白色背景
$polygon_color = imagecolorallocate($image, 0, 0, 255); // 藍色多邊形
// 填充背景色
imagefill($image, 0, 0, $background_color);
// 多邊形的頂點坐標
$points = array(
150, 150,
350, 150,
400, 350,
200, 400,
100, 300
);
// 繪製多邊形
imagepolygon($image, $points, 5, $polygon_color);
// 輸出圖像
header('Content-Type: image/png');
imagepng($image);
// 銷毀圖像資源
imagedestroy($image);
?>