碰到php使用GD图像库绘制输出图像出现乱码问题和图片上输出中文出现乱码问题,今天找了不少方法,总算找到一个可以解决的方法。
源码:
<html> <head> <title>PHP 图像测试</title> </head> <body> <?php #创建背景图像 $im = @imagecreate(500,500) or die(没有安装GD图像库<br>); #设置背景颜色 $bgCol=imagecolorallocate($im,255,0,0); #设置字体颜色 $texCol=imagecolorallocate($im,255,255,0); $motto = I love my baby! 我家宝贝聪明可爱漂亮; $motto = iconv(gb2312, utf-8, $motto); #在背景图像上输入文字 imagestring($im,3,5,5,$motto,$texCol); #输出图像 header(Content-Type: image/png); imagepng($im); #清除所有资源 imagedestroy($im); ?> </body> </html>
运行后得到的结果:
<html> <head> <title>PHP ͼ������</title> </head> <body> �PNG IHDR���M�PLTE���lۜ�IDATx���1 �0�ᔀ]*��W�:/�ر��C����ɥ��1N���?^������M��c��N���>t1�+�w�1 �Z۷�+��<��7���y�ݏ�.�}�T�ݧ_��?�/o�m��IEND�B`�</body> </html>
(1)解决方法:在$im = @imagecreate(500,500) or die(没有安装GD图像库<br>);前面加上ob_clean();先清除缓冲区。即可显示图片,但图片上的文字只能显示英文和数字,中文会出现乱码。
(2)imagestring 默认英文编码,只支持UTF-8,所以中文会出现乱码,应采用imagettftext($im,10,30,0,100,$texCol,c:/windows/fonts/simhei.ttf,$motto);。
c:/windows/fonts/simhei.ttf,系统自带的黑体。
以上就是图片输出乱码和图片上中文乱码的解决方法。