PHP imagecreate - 生成自定义图片
该方法是根据字符的长度改变字体的大小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
$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