php imagepng无法显示的解决办法:1、用第三方编码工具把文件格式保存为无BOM的utf-8格式;2、利用“ob_clean();”清空缓冲区。

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

php imagepng无法显示怎么办?

PHP 使用GD 库绘制图像,无法显示的问题

根据官方GD 库绘制图像文档样式

原基本样式:

$width = 120;
$height = 50;
$img = @imagecreatetruecolor($width, $height) or die('Cannot Initialize new GD image stream');;//新建一个GD图像资源
$img_bgcolor = imagecolorallocate($img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));//背景色
$img_textcolor = imagecolorallocate($img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));//字体颜色
$img_rectangle = imagefilledrectangle($img,0,0,$width, $height,$img_bgcolor);//画一个矩形图像
imagestring($img, 1, 5, 5, 'A Simple Text String', $img_textcolor);
// 输出图像
header("Content-type:image/png");
imagepng($img);
imagedestroy($img);//销毁图像

但在实际运用中会出现无法正常显示图像的问题:

出现的原因可能有以下几种情况:

  原因1:文件编码格式带有BOM 头,解决方法,用第3方编码工具,sublime 或 notepad++ 等把 文件格式保存为无BOM 的utf-8 格式

  原因2:PHP缓冲区的问题,解决方法利用 ob_clean();清空缓冲区。

常用缓冲区函数 ob 函数

参考:http://php.net/manual/zh/ref.outcontrol.php

ob_get_contents() - 返回输出缓冲区的内容

ob_flush() - 冲刷出(送出)输出缓冲区中的内容

ob_clean() - 清空(擦掉)输出缓冲区

ob_end_flush() - 冲刷出(送出)输出缓冲区内容并关闭缓冲

ob_end_clean() - 清空(擦除)缓冲区并关闭输出缓冲

flush() - 刷新输出缓冲

判断GD库是否安装

function_exists('imagecreate') 通过判断扩展库提供的方法是否存在来判断get_extension_funcs() ,但不全面,不

php imagepng无法显示怎么办