Home  >  Article  >  php教程  >  php绘图之在图片上写中文和英文的方法

php绘图之在图片上写中文和英文的方法

WBOY
WBOYOriginal
2016-06-06 20:12:281063browse

这篇文章主要介绍了php绘图之在图片上写中文和英文的方法,涉及GD库中imagestring和imagettftext方法的使用技巧,需要的朋友可以参考下

本文实例讲述了php绘图之在图片上写中文和英文的方法。分享给大家供大家参考。具体如下:

第一种方法,只能写英文,中文会出现乱码

复制代码 代码如下:

//1、创建画布
$im = imagecreatetruecolor(300,200);//新建一个真彩色图像,默认背景是黑色,返回图像标识符。另外还有一个函数 imagecreate 已经不推荐使用。
$red = imagecolorallocate($im,255,0,0);
//2、写字
$str = "hello,world";
imagestring($im,5,30,60,$str,$red);//参数说明:5-指文字的大小。函数 imagestring 不能写中文
//3、输出图像
header("content-type: image/png");
imagepng($im);//输出到页面。如果有第二个参数[,$filename],则表示保存图像
//4、销毁图像,释放内存
imagedestroy($im);
?>

第二种方法:写中文

复制代码 代码如下:

//1、创建画布
$im = imagecreatetruecolor(300,200);//新建一个真彩色图像,默认背景是黑色,,返回图像标识符。另外还有一个函数 imagecreate 已经不推荐使用。
$red = imagecolorallocate($im,255,0,0);
//2、写字
$str = iconv("gb2312","utf-8","北京,你早!hello,world");//文件格式为gbk,而这里转为uft-8格式,才能正常输出,否则也为乱码。表示不明
imagettftext($im,12,rand(0,20),20,100,$red,"simhei.ttf",$str);
//3、输出图像
header("content-type: image/png");
imagepng($im);//输出到页面。如果有第二个参数[,$filename],则表示保存图像
//4、销毁图像,释放内存
imagedestroy($im);
?>


imagettftext() 函数远强于imagestring() 函数,表现在这几个方面:

(1)imagettftext() 可以输出中文和英文,可以指定字体;imagestring() 只能输出英文,只能使用默认字体。
(2)imagettftext() 字体大小可以无限大;imagestring() 字体只有1~5号大小。
(3)imagettftext() 输出的字体可以变换角度;imagestring() 只能水平输出。

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn