WordPress純代碼生成文章海報圖片實現分享功能,實現這個功能需要依賴于PHP的GD庫,沒有就不行喲,虛擬主機用戶要好好看看是否支持喲。主要使用了PHP的復制圖像,文本轉圖像等函數實現的,下面我們一起來看看實現代碼。
$im = imagecreatetruecolor(440, 700) or die("不能初始化新的 GD 圖像流");//創建一張空白圖像
$_bg_color = imagecolorallocate($im, 255,255,255); //創建顏色,返回顏色標識符
imagefill($im, 0, 0, $_bg_color); //初始化圖像背景為$_bg_color
$bg=imagecreatefromstring(file_get_contents($bigImgPath));//獲取網絡圖片
$src_info = getimagesize($bigImgPath); //得到圖片大小
$bgsf = imagecreatetruecolor(440, 300); //創建一個畫布
imagecopyresampled($bgsf,$bg,0,0,0,0,440,300,$src_info[0],$src_info[1]);//縮放圖像
imagecopymerge($im,$bgsf,0,0,0,0,440,300,100);//復制合成
$_text_color = imagecolorallocate($im, 0,0,0);//文字顏色
$fontpath='msyh.ttf';//字體文件路徑
$im=textcl($im,$_text_color,$str,$fontSize,$fontpath,330,'');//處理多行文字
$im=textcl($im,$_text_color,$description,$desfontSize,$fontpath,410,' ');
$qecode=imagecreatefromstring(file_get_contents($ewm));//獲取網絡圖片
$ewm_info = getimagesize($ewm); //得到圖片大小
imagecopymerge($im,$qecode,10,500,0,0,$ewm_info[0],$ewm_info[1],100);//復制合成
$dateimg = imagecreatetruecolor(200, 200); //創建一個畫布
imagefill($dateimg, 0, 0, $_bg_color); //填充顏色
imagettftext($dateimg, $datefontsize, 0,0, 50, $_text_color,$fontpath,$domain);//文字轉圖片
imagettftext($dateimg, $desfontSize, 0,0, 90, $_text_color,$fontpath,'————————————————————————');
imagettftext($dateimg, $desfontSize, 0,20, 120, $_text_color,$fontpath,$datestr);
imagecopymerge($im,$dateimg,200,520,0,0,200,200,100);//復制合成
header("Content-type: image/png"); //以圖像類型輸出
imagepng($im);//展示圖像
imagedestroy($im); //銷毀圖像,釋放資源哈哈哈,是不是覺得很好理解?每一行都有注釋喲。這里要說兩句,有個字體文件,這個大家喜歡什么字體就去下載什么字體就好,字體文件是多平臺通用的,不用擔心不兼容。還有一個多行文字轉圖片的問題,我這里把它寫成了一個方法,對于標題和描述都可以使用,節省代碼。
//自動文字換行計算
function textcl($img,$_text_color,$str,$fontSize,$fontpath,$Y,$before){
for ($i=0;$i<mb_strlen($str);$i++) {
$letter[] = mb_substr($str, $i, 1,'utf-8');
}
$content=$before;
foreach ($letter as $l) {
$teststr = $content." ".$l;
$fontBox = imagettfbbox($fontSize, 0, $fontpath, $teststr);
if (($fontBox[2] > 400) && ($content !== "")) {
$content .= "\n";
}
$content .= $l;
}
imagettftext($img, $fontSize, 0, ceil((440 - $fontBox[2]) / 2), $Y, $_text_color, $fontpath, $content );
return $img;
}參數說明
1、圖像載體
2、字體顏色
3、字符串內容
4、字體大小
5、字體路徑
6、添加在字符串之前(用于首行縮進)
使用方法
準備必須內容,主要有以下內容:
$bigImgPath=’最上面的圖片鏈接’; $str =’標題’; $description=’描述(注意有字數限制,不然會超出圖像)’; $ewm=’https://www.daimadog.com/qrcode.php?cont=https://www.daimadog.com/4077.html&rc=L&size=150′; //二維碼圖像地址,我這里使用的是代碼狗博客提供的二維碼生成接口 $datestr=’時間字符串’; $domain=’域名字符串’; $fontSize=22;//標題字體大小,22磅 $desfontSize=14;//描述字體大小 $datefontsize=14;//日期字體大小






