接收前端发送的文本,使用php内置函数实现文本转换图片
<?php
header('Content-Type: text/html; charset=utf-8');
$content = file_get_contents("php://input");
$content = json_decode($content,true);
$type = $content['type'];
$errcode = 0;
$errtext = "";
$myJson = array();
$greetingpath = 'static/greeting/';//合成图片目录
$jsonfile = 'config.json';//语言合成config文件
$fontttf = "./static/dist/fonts/xiekai.ttf"; //文本字体
if(!$type)
$errtext = "error param";
if($errtext == ""){
switch ($type) {
case 'setgreeting':
$greeting = $content['greeting'];
$width = 1600;
$height = 450;
$fontsize = 50;
$strlength = mb_strlen($greeting)*$fontsize;
//imgx和imgy用于文本的垂直居中显示,目前只考虑单行文本
$imgx = ($width-$strlength)/2;
$imgy = $height/2;
$myImage=imagecreatetruecolor($width,$height); //参数为宽度和高度
$background = imagecolorallocate($myImage, 0, 0, 0);//背景颜色
imagefill($myImage, 0, 0, $background);
$red= ImageColorAllocate($myImage, 255, 0, 0);//字体颜色
imagettftext($myImage, $fontsize, 0, $imgx, $imgy, $red, $fontttf, $greeting);
$pathname = date('Ymd',time());
$filename = time();
$new_file = $greetingpath.$pathname."/";
if(!file_exists($new_file)){
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700,true);
}
$new_file = $new_file.$filename.".jpg";
imagepng($myImage,$new_file);
imagedestroy($myImage);
$myJson['picurl'] ='http://'.$_SERVER['HTTP_HOST'].'/'.$new_file;//返回生成图片的url地址
break;
default:
$errtext = "unkonw type";
break;
}
}
if($errtext !='')
$errcode = 1;
$myJson['errcode'] = $errcode;
$myJson['errtext'] = $errtext;
echo json_encode($myJson);
生成效果