最近看了几个关于php生成图片的例子,写的都很复杂,也不实用。自己写了个简单的例子,给有缘人参考下。
一共有4个文件(运行环境:php5.3-nts+Apache)
1.html 用来输入要转换成图片的文字
2.html 调用并传值pic.php生成图片
pic.php 生成图片
simhei.ttf 字体文件
1.html(原理很简单,把文本框的内容通过get方式传到2.html页面)
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<title>请输入文字-https://blog.csdn.net/cool4800</title>
</head>
<SCRIPT LANGUAGE="JavaScript">
function test(){
var s = document.getElementById("txt");
location.href="2.html?"+"txt="+encodeURI(s.value);
}
</SCRIPT>
<body>
<center>
请输入要转换的文字:<input type="text" id="txt">
</br></br>
<input type="button" value="转图片" onClick="test()"/>
<BR>
<BR>
<a href="https://blog.csdn.net/cool4800">https://blog.csdn.net/cool4800</a>
</center>
</body>
</html>
2.html(获取1.html传来的内容)
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<title>已生成图片-https://blog.csdn.net/cool4800</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var loc = location.href;
var n1 = loc.length;
var n2 = loc.indexOf("=");
var id = decodeURI(loc.substr(n2+1, n1-n2));
document.write("<img src=\"pic.php?key="+id+"\">");
</script><BR>
<a href="https://blog.csdn.net/cool4800">https://blog.csdn.net/cool4800</a>
</body>
</html>
pic.php (另外把imagecreate换成imagecreatefromstring就可以在指定图片上的写入文字)
<?php
$im = imagecreate(500, 100) or die("Cannot Initialize new GD image stream");
// 图片大小-https://blog.csdn.net/cool4800
ImageColorAllocate($im,140,140,140);
// 背景颜色-https://blog.csdn.net/cool4800
$text_color = imagecolorallocate($im, 194, 16, 16);
// 文字颜色-https://blog.csdn.net/cool4800
$font="simhei.ttf";
//使用字体-https://blog.csdn.net/cool4800
$str=$_GET['key'];
//需要转换的文字-https://blog.csdn.net/cool4800
$strpic = iconv("GB2312","UTF-8",$str);
//字体编辑转换-https://blog.csdn.net/cool4800
imagettftext($im,50,0,0,80,$text_color,$font,$strpic);
//成生图片-https://blog.csdn.net/cool4800
ImagePNG($im);
imagedestroy($im);
?>
php生成指定文字图片例子源码下载 https://download.csdn.net/download/cool4800/12150542
ps另外有能力的稍微改一改就是朋友圈内比较火的一个整蛊游戏