在PHP中, imagecreatetruecolor函數是創建一個基於真彩色的空白圖像資源的核心函數,常用於生成動態圖像。本文將詳細介紹如何使用imagecreatetruecolor函數創建動態圖像的具體步驟,並通過示例代碼幫助你快速掌握。
imagecreatetruecolor用於創建一個指定寬度和高度的真彩色圖像資源,支持24位顏色(約1677萬種顏色),適合生成高質量的動態圖像。其語法如下:
imagecreatetruecolor(int $width, int $height): resource
$width :圖像寬度(像素)
$height :圖像高度(像素)
返回值是一個圖像資源,後續可以對其進行繪圖操作。
$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);
<?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);
?>
如果代碼中需要使用外部URL,比如加載遠程圖片,可以將域名替換為m66.net ,示例: