利用 PHP GD 庫動態生成帶水印的圖片,結合資料庫內容輸出標題、作者與正文,最後疊加 Logo 浮水印,適用於文章分享圖、海報自動生成等場景。
<?php
header("Content-type: image/png");
// 連接資料庫(建議改用 PDO 或 mysqli)
$conn = mysql_connect("localhost", "root", "");
$colname_rs_article = $_GET['id'];
mysql_select_db("cms", $conn);
$query_rs_article = sprintf("SELECT * FROM articles WHERE article_id = %s", $colname_rs_article);
$rs_article = mysql_query($query_rs_article, $conn) or die(mysql_error());
$row_rs_article = mysql_fetch_assoc($rs_article);
// 建立畫布
$image = imagecreatetruecolor(700, 1000);
$bg = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg);
// 文字顏色
$text_color = imagecolorallocate($image, 0, 0, 0);
// 繪製文章內容
imagestring($image, 5, 0, 0, $row_rs_article['title'], $text_color);
imagestring($image, 3, 0, 20, $row_rs_article['author'], $text_color);
imagestring($image, 4, 0, 60, $row_rs_article['content'], $text_color);
// 載入並合成水印圖片
$logo = imagecreatefrompng('logo.png');
$logoW = imagesx($logo);
$logoH = imagesy($logo);
imagecopy($image, $logo, 0, 0, 0, 0, $logoW, $logoH);
// 輸出與釋放資源
imagejpeg($image);
imagedestroy($logo);
imagedestroy($image);
?>
imagecreatetruecolor():建立真彩色畫布imagecolorallocate():分配顏色識別碼imagestring():繪製水平字串(字型大小 1-5)imagecreatefrompng():從 PNG 檔建立圖片資源imagecopy():將來源圖片複製到目標畫布imagedestroy():釋放記憶體資源mysql_* 函數升級為 PDO 或 mysqli(舊版已棄用)imagettftext() 支援 TrueType 字型,解決中文顯示問題