三大常見圖片操作一次掌握
- 圖片上寫字:
imagestring()(內建字體)或 imagettftext()(TTF 字體)。
- 等比例縮放:
getimagesize() 取得尺寸 → 計算比例 → imagecopyresampled()。
- 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 |