首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP GD 庫實作動態圖片水印:從資料庫讀取內容合成

     編輯:PHP 相關知識

利用 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():釋放記憶體資源

改進建議

  1. 將 mysql_* 函數升級為 PDO 或 mysqli(舊版已棄用)
  2. 使用 imagettftext() 支援 TrueType 字型,解決中文顯示問題
  3. 加入參數驗證與 SQL 注入防護
  4. 調整水印位置(如右下角)避免遮蓋文字
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved