該方法是根據字符的長度改變字體的大小php
function generateCover($content,$author,$date)//$content名稱 $author做者 $date日期 { $width = 640; $height = 360; $myImage = ImageCreate($width,$height); //參數爲寬度和高度 $white = ImageColorAllocate($myImage, 255, 255, 255);//白色 $blue = ImageColorAllocate($myImage, 0, 0, 255);//藍色 imagefill($myImage, 0, 0, $blue);//藍色背景 $font = "/src/style/fonts/msyh.ttf";//下載的字體,可自行百度搜下載引用 $filePathDir = "file/cover/" . date("Ymd") . '/'; if (!is_dir($filePathDir)) { mkdir($filePathDir, 0777, true);//建立圖片的存儲文件夾 } $filePath = $filePathDir.md5(time()).'.jpg';//圖片的路徑 $date = date("Y-m-d",strtotime($date)); if(mb_strlen($content) <= 10) {//字符長度大於等於10 contentlenth1($myImage,$content,$author,$date,$font,$width,$height,$white,$filePath); }else { contentlenth2($myImage,$content,$author,$date,$font,$width,$height,$white,$filePath); } return $filePath; }
//標題長度小於等於10字體
function contentlenth1($myImage,$string,$author,$date,$font,$width,$height,$white,$filePath) { $textlen = mb_strlen($string); $value = $textlen - 4; if ($value < 0) $value = 0; $fontsize = 3.5 * (6 - $value) + 30; $fontwidth = $fontsize * 1.35; $fontheight = $fontsize * 1; for ($i=0;$i<mb_strlen($string);$i++) { $letter[] = mb_substr($string, $i, 1); } imagettftext($myImage, $fontsize, 0, ($width-$fontwidth*mb_strlen($string))/2, ($height * 0.7 + $fontheight) / 2, $white, $font, $string); $authorrHeight = ($height * 0.15 + 20)/ 2 + $height * 0.55; $dateHeight = ($height * 0.15 + 20) / 2 + $height * 0.75; imagettftext($myImage, 20, 0, ($width-20*1.35*mb_strlen($author))/2, $authorrHeight, $white, $font, $author); imagettftext($myImage, 20, 0, ($width-0.72*20*strlen($date))/2, $dateHeight, $white, $font, $date); imagepng($myImage,$filePath); }
//標題長度超過10code
function contentlenth2($myImage,$string,$author,$date,$font,$width,$height,$white,$filePath) { $toplen = ceil(mb_strlen($string) * 0.4); $texttop = mb_substr($string, 0, $toplen); $texttoplen = mb_strlen($texttop); $value = $texttoplen - 4; if ($value < 0) $value = 0; $fontsize = 2 * (6 - $value) + 30; $fontwidth = $fontsize * 1.35; $fontheight = $fontsize * 1; imagettftext($myImage, $fontsize, 0, ($width-$fontwidth*mb_strlen($texttop))/2, ($height * 0.7 + $fontheight) / 2 - $fontsize, $white, $font, $texttop); $textbottom = mb_substr($string, $toplen, mb_strlen($string) - $toplen); imagettftext($myImage, $fontsize, 0, ($width-$fontwidth*mb_strlen($textbottom))/2, ($height * 0.7 + $fontheight) / 2 + $fontsize, $white, $font, $textbottom); $authorrHeight = ($height * 0.15 + 20)/ 2 + $height * 0.6; $dateHeight = ($height * 0.15 + 20) / 2 + $height * 0.75; imagettftext($myImage, 20, 0, ($width-20*1.35*mb_strlen($author))/2, $authorrHeight, $white, $font, $author); imagettftext($myImage, 20, 0, ($width-20*0.72*strlen($date))/2, $dateHeight, $white, $font, $date); imagepng($myImage,$filePath); }
效果圖:
blog