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

PHP 圖片文字繪製、等比縮放、Base64 解碼顯示三合一實戰範例

     編輯:PHP 相關知識

三大常見圖片操作一次掌握

  1. 圖片上寫字:imagestring()(內建字體)或 imagettftext()(TTF 字體)。
  2. 等比例縮放:getimagesize() 取得尺寸 → 計算比例 → imagecopyresampled()。
  3. Base64 字串解碼顯示:base64_decode() → imagecreatefromstring() → 輸出。

1. 圖片上寫字(Hello World)

<?php
header('Content-Type: image/png');
$im = @imagecreate(150, 50) or die('GD 初始化失敗');
$bg = imagecolorallocate($im, 255,255,255);
$txt = imagecolorallocate($im, 233,14,91);
imagestring($im, 3, 5, 5, 'Hello World', $txt); // 字體 3、座標 (5,5)
imagepng($im);
imagedestroy($im);
?>

2. 等比例縮小 50%

<?php
$src = 'photo.jpg';
$pct = 0.5;
header('Content-Type: image/jpeg');
list($w,$h) = getimagesize($src);
$nw = (int)($w * $pct); $nh = (int)($h * $pct);
$dst = imagecreatetruecolor($nw, $nh);
$srcIm = imagecreatefromjpeg($src);
imagecopyresized($dst, $srcIm, 0,0,0,0, $nw,$nh, $w,$h); // 或 resampled
imagejpeg($dst);
imagedestroy($dst); imagedestroy($srcIm);
?>

3. Base64 字串解碼為圖片

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAAB...'; // 略
$bin = base64_decode($data);
$im = imagecreatefromstring($bin);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
} else {
    echo 'Base64 解碼失敗或非有效圖片資料';
}
?>

進階:TTF 中文字體繪製

<?php
header('Content-Type: image/png');
$im = imagecreatetruecolor(300, 100);
$bg = imagecolorallocate($im, 240,248,255);
$txt = imagecolorallocate($im, 25,25,112);
imagefill($im, 0,0, $bg);
$font = __DIR__ . '/fonts/msjh.ttc'; // 微軟正黑體
$text = 'PHP 圖片處理教學';
imagettftext($im, 24, 0, 20, 60, $txt, $font, $text);
imagepng($im);
imagedestroy($im);
?>

常見問題排查

現象原因解決
imagettftext 不顯示中文字體檔路徑錯誤、字體不支援中文、字串非 UTF-8確認字體路徑、用 msjh.ttc/simsun.ttc、確保 PHP 檔案存為 UTF-8
縮圖變形寬高比計算錯誤用 min($maxW/$w, $maxH/$h) 取較小比例
Base64 解碼失敗字串含空白/換行、非標準 Base64先 str_replace([' ','\n','\r'],'',$str) 再 decode
輸出圖片損壞header 之前有輸出、imagepng 後有額外輸出確保 header 前無 echo/空白、腳本結束用 exit
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved