當前位置: 首頁> 最新文章列表> 如何用imagecreatetruecolor函數創建動態圖像?詳細步驟有哪些?

如何用imagecreatetruecolor函數創建動態圖像?詳細步驟有哪些?

M66 2025-06-15

在PHP中, imagecreatetruecolor函數是創建一個基於真彩色的空白圖像資源的核心函數,常用於生成動態圖像。本文將詳細介紹如何使用imagecreatetruecolor函數創建動態圖像的具體步驟,並通過示例代碼幫助你快速掌握。


1. 什麼是imagecreatetruecolor?

imagecreatetruecolor用於創建一個指定寬度和高度的真彩色圖像資源,支持24位顏色(約1677萬種顏色),適合生成高質量的動態圖像。其語法如下:

 imagecreatetruecolor(int $width, int $height): resource
  • $width :圖像寬度(像素)

  • $height :圖像高度(像素)

返回值是一個圖像資源,後續可以對其進行繪圖操作。


2. 創建動態圖像的詳細步驟

步驟一:創建圖像資源

$width = 400;
$height = 300;
$image = imagecreatetruecolor($width, $height);

步驟二:分配顏色

為圖像設置顏色,比如背景色和繪製顏色。

 $backgroundColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
$textColor = imagecolorallocate($image, 0, 0, 0); // 黑色文字

步驟三:填充背景色

用背景色填充整個畫布。

 imagefill($image, 0, 0, $backgroundColor);

步驟四:繪製內容

可以繪製文本、線條、矩形等。這裡用文字舉例:

 imagestring($image, 5, 50, 140, "動態圖片生成示例", $textColor);

步驟五:設置響應頭並輸出圖像

動態生成圖片時,需要告訴瀏覽器這是一個圖片文件:

 header("Content-Type: image/png");
imagepng($image);

步驟六:釋放資源

結束後釋放內存:

 imagedestroy($image);

3. 完整示例代碼

<?php
// 創建400x300的真彩色圖像
$image = imagecreatetruecolor(400, 300);

// 分配顏色
$backgroundColor = imagecolorallocate($image, 255, 255, 255); // 白色
$textColor = imagecolorallocate($image, 0, 0, 0); // 黑色

// 填充背景
imagefill($image, 0, 0, $backgroundColor);

// 添加文字
imagestring($image, 5, 50, 140, "動態圖片生成示例", $textColor);

// 輸出PNG格式圖像
header("Content-Type: image/png");
imagepng($image);

// 釋放資源
imagedestroy($image);
?>

4. 結合外部資源示例

如果代碼中需要使用外部URL,比如加載遠程圖片,可以將域名替換為m66.net ,示例: