php The solution to the problem that imagepng cannot be displayed: 1. Use a third-party encoding tool to save the file format as utf-8 format without BOM; 2. Use "ob_clean();" to clear the buffer.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
What should I do if php imagepng cannot be displayed?
PHP uses the GD library to draw images and cannot display the problem
According to the official GD library to draw image document styles
Original basic style:
$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);//销毁图像
However, in actual application, there may be a problem that the image cannot be displayed normally:
The reasons may be as follows:
Reason 1: The file encoding format has a BOM header. The solution is to use a third-party encoding tool, sublime or notepad, etc. to save the file format as a BOM-free utf-8 format
Reason 2: PHP buffer problem, the solution is to use ob_clean(); to clear the buffer.
Commonly used buffer function ob function
Reference: http://php.net/manual/zh/ref.outcontrol.php
ob_get_contents() - Returns the contents of the output buffer
ob_flush() - Flushes out (sends out) the contents of the output buffer
ob_clean() - Clears (erases) ) Output buffer
ob_end_flush() - Flush out (send out) the contents of the output buffer and close the buffer
ob_end_clean() - Clear (erase) the buffer and close the output buffer
flush() - Flush the output buffer
Determine whether the GD library is installed
function_exists('imagecreate') Determine whether the method provided by the extension library exists get_extension_funcs(), but it is not comprehensive and is not recommended (because some extensions do not provide functions)
in_array('extension name', get_loaded_extensions()) By verifying whether the extension is in the loaded extension Determine whether it is installed (comprehensive, but not concise)
extension_loade('extension library name') Verify by judging whether the extension library is loaded (comprehensive, but not concise, it is recommended to use this method to verify whether the extension is installed and loaded)
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What to do if php imagepng cannot be displayed. For more information, please follow other related articles on the PHP Chinese website!