如何使用php快速制作文字生成图片
制作文字转图片其实还是很简单的
不过由于平时用的比较少,就容易忘
为了方便以后使用,这里就留着以后查看吧(不就是复制粘贴嘛==)
define('ROOT', dirname(dirname(__FILE__)) . '/');
$conf['key'] = ''; //认证密钥,防止被滥用
@header('Content-Type: application/json; charset=UTF-8');
switch ($act) {
case 'getTextImage': //获取文本图片
$width = $_POST['width'] > 0 ? intval(addslashes($_POST['width'])) : 500;//图片宽度
$text = trim(addslashes($_POST['text']));//要生成的文字
$key = trim(addslashes($_POST['key']));
if ($key !== $conf['key']) {
exit('{"code":-1,"msg":"key is Error"}');
}
$arr = explode("\n", $text);
$lines = count($arr);
$height = $lines * 21 + 80; //预估图片高度
$margin_left = 20;//x坐标 也就是左边距
$margin_top = 50;//y坐标 也就是顶边距
$fontPath = ROOT . 'assets/fonts/simsun.ttc';//ttf字体库文件,不支持或没有中文文字会不正常或报错
$im = @imagecreate($width, $height) or exit('{"code":-1,"msg":"GD library Initialize is Fail!"}');
$bg_color = imagecolorallocate($im, 225, 255, 255); //定义背景颜色
$text_color = imagecolorallocate($im, 5, 5, 0); //定义文本颜色
$imageData = '';
$result = [];
if (imagettftext($im, 12, 0, $margin_left, $margin_top, $text_color, $fontPath, $text)) {
$result['code'] = 0;
$result['code'] = 0;
$result['msg'] = ['succ'];
ob_start();
imagepng($im);
$imageData = base64_encode(ob_get_contents()); //获得png格式图像数据,使用时需要使用base64解密才能使用
ob_end_clean();
} else {
$result['code'] = -1;
$result['msg'] = '生成图片失败!';
}
$result['data'] = $imageData;
exit(json_encode($result));
break;
default:
exit('{"code":-5,"msg":"No Act"}');
break;
}代码都很简单,写的不好见谅哦~
-- 展开阅读全文 --
