從資料庫讀取文章標題、作者、內容,繪製至畫布並疊加 Logo 水印,最終輸出 PNG 圖片。適用於生成分享卡片、防盜圖等場景。
<?php
header('Content-Type: image/png');
// 1. 資料庫連線(建議改用 PDO/MySQLi)
$conn = mysqli_connect('localhost', 'root', '', 'cms');
$articleId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$sql = 'SELECT title, author, content FROM articles WHERE article_id = ?';
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'i', $articleId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$article = mysqli_fetch_assoc($result);
// 2. 建立畫布
$width = 700; $height = 1000;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255); // 白底
imagefill($image, 0, 0, $bgColor);
$textColor = imagecolorallocate($image, 0, 0, 0); // 黑字
// 3. 繪製文字(建議改用 imagettftext 支援中文/換行)
imagestring($image, 5, 20, 20, $article['title'], $textColor);
imagestring($image, 3, 20, 60, '作者: ' . $article['author'], $textColor);
// 內容過長需自行換行處理,此處示意
imagestring($image, 4, 20, 100, mb_substr($article['content'], 0, 80), $textColor);
// 4. 疊加水印圖片
$logo = imagecreatefrompng('logo.png');
$logoW = imagesx($logo);
$logoH = imagesy($logo);
// 置中偏下
$destX = ($width - $logoW) / 2;
$destY = $height - $logoH - 20;
imagecopy($image, $logo, $destX, $destY, 0, 0, $logoW, $logoH);
// 5. 輸出並釋放資源
imagepng($image);
imagedestroy($logo);
imagedestroy($image);
mysqli_close($conn);
?>
mysqli 預處理語句防止 SQL 注入。header('Content-Type: image/png') 必須在任何輸出之前。imagettftext() 載入 TTF 字體,imagestring() 僅支援內建拉丁字體。imagecopymerge() 控制。