引言

準(zhǔn)備工作

在開始之前,請確保你的服務(wù)器已安裝PHP和GD庫。GD庫是PHP的一個圖像處理庫,支持多種圖像格式。

1. 創(chuàng)建圖片資源

// 創(chuàng)建一個空白圖像,指定寬度和高度
$image = imagecreatetruecolor(100, 50);

// 設(shè)置背景顏色
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);

2. 繪制圖形

在圖像資源上繪制各種圖形,如矩形、圓形、線條等。以下是一些常用的繪圖函數(shù):

// 繪制矩形
$red = imagecolorallocate($image, 255, 0, 0);
imagerectangle($image, 10, 10, 90, 40, $red);

// 繪制圓形
$blue = imagecolorallocate($image, 0, 0, 255);
imagefilledellipse($image, 50, 25, 40, 40, $blue);

// 繪制線條
$green = imagecolorallocate($image, 0, 255, 0);
imageline($image, 10, 10, 90, 40, $green);

3. 添加文字

在圖像上添加文字,可以使用以下函數(shù):

// 設(shè)置字體路徑
$font_path = 'arial.ttf';

// 加載字體
$font = imagettfbbox(20, 0, $font_path, 'Hello, World!');

// 計算文字位置
$x = (100 - $font[4]) / 2;
$y = (50 - ($font[5] + $font[7])) / 2;

// 添加文字
$black = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, $x, $y, $black, $font_path, 'Hello, World!');

4. 保存圖片

將圖像保存到服務(wù)器上的指定路徑:

// 設(shè)置圖片格式
imagejpeg($image, 'image.jpg');

// 釋放圖像資源
imagedestroy($image);

5. 輸出圖片

header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);

總結(jié)