PHP圖片文字合成居中
- 2019 年 12 月 19 日
- 筆記
PHP處理圖片
PHP使用GD庫創建和處理包括GIF,PNG,jpef,wbmp以及xpm在內的多種格式的圖像。
以下教程:圖片合成文字,實現合成文字水平、垂直居中。
讀取圖片資源
imagecreatefrom 系列函數用於從文件或 URL 載入一幅圖像,成功返回圖像資源,失敗則返回一個空字符串。
根據圖片格式選用不同函數
imagecreatefromgif():創建一塊畫布,並從 GIF 文件或 URL 地址載入一副圖像 imagecreatefromjpeg():創建一塊畫布,並從 JPEG 文件或 URL 地址載入一副圖像 imagecreatefrompng():創建一塊畫布,並從 PNG 文件或 URL 地址載入一副圖像 imagecreatefromwbmp():創建一塊畫布,並從 WBMP 文件或 URL 地址載入一副圖像 imagecreatefromstring():創建一塊畫布,並從字符串中的圖像流新建一副圖像
獲取圖片尺寸
imagesx($image); imagesy($image);
創建顏色
imagecolorallocatealpha(resource $image , int $red , int $green , int $blue , int $alpha); // 帶透明度 imagecolorallocate(resource $image , int $red , int $green , int $blue); // 普通
獲取文字內容所需尺寸
imagettfbbox ( float $size, float $angle, string $fontfile, string $text):array
取得使用 TrueType 字體的文本的範圍。(種類型字體文件的擴展名是.ttf,類型代碼是tfil。)
以上是每個步驟使用的關鍵函數說明。以下是完整代碼示例。
<?php /** * Created by PhpStorm. * User: Siam * Date: 2019/2/4 0004 * Time: 下午 10:58 */ $main = imagecreatefromjpeg('./test.jpg'); $fontSize = 38; $width = imagesx($main); $height = imagesy($main); //1.設置字體的路徑 $font = "./t.ttf"; //2.填寫水印內容 $content = "My name is Siam,中文是宣言"; //3.設置字體顏色和透明度 $color = imagecolorallocatealpha($main, 255, 255, 255, 0); $fontBox = imagettfbbox($fontSize, 0, $font, $content);//獲取文字所需的尺寸大小 //4.寫入文字 (圖片資源,字體大小,旋轉角度,坐標x,坐標y,顏色,字體文件,內容) imagettftext($main, $fontSize, 0, ceil(($width - $fontBox[2]) / 2), ceil(($height - $fontBox[1] - $fontBox[7]) / 2), $color, $font, $content); // 瀏覽器輸出 也可以換成保存新圖片資源 header("Content-type:jpg"); imagejpeg($main);
效果:


最關鍵的步驟是獲取到文字內容所需的尺寸大小
原圖的大小 – 文字內容的大小 = 剩餘空白大小; 剩餘空白大小 / 2 的效果就是自動居中。
我們可以在以上基礎上封裝成一個靈活的函數
<?php function imageAddText($path, $content, $x = 'auto', $y = 'auto', $fontSize = 38, $font = './t.ttf'){ $temp = array(1=>'gif', 2=>'jpeg', 3=>'png'); // 獲取圖片信息 $imageInfo = getimagesize($path); $imageType = $temp[$imageInfo[2]]; $getfunc = "imagecreatefrom$imageType"; $outfunc = "image$imageType"; $resource = $getfunc($path); $width = imagesx($resource); $height = imagesy($resource); $color = imagecolorallocatealpha($resource, 255, 255, 255, 0); $fontBox = imagettfbbox($fontSize, 0, $font, $content);//文字水平居中實質 if ($x === 'auto'){ $x = ceil(($width - $fontBox[2]) / 2); } if ($y === 'auto'){ $y = ceil(($height - $fontBox[1] - $fontBox[7]) / 2); } imagettftext($resource, $fontSize, 0, $x, $y, $color, $font, $content); /*輸出圖片*/ //瀏覽器輸出 header("Content-type:".$imageType); $outfunc($resource); } // 自動居中 // imageAddText('./test.jpg', 'My name is Siam,中文名是宣言'); // 聲明x y值 // imageAddText('./test.jpg', 'My name is Siam,中文名是宣言',200); // imageAddText('./test.jpg', 'My name is Siam,中文名是宣言','auto', '300');