当前位置:首页 > 建站笔记 > 正文

如何解决php输出图片并显示中文乱码问题

php输出图片并显示中文乱码的解决办法:1、在PHP代码前加上ob_clean()清除缓冲区;2、设置UTF-8编码即可。

本文操作环境:Windows7系统、PHP7.1版、DELL G3电脑

如何解决php输出图片并显示中文乱码问题?

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",系统自带的黑体。

发表评论