Home > Article > Backend Development > What should I do if PHP cannot display the picture using GD?
Solution to the problem that PHP cannot display pictures using gd: 1. 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
PHP uses the GD library to draw images and cannot display the problem
Draw image document style based on the official GD library
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);//销毁图像
But it will not work in actual application The problem of normal display of images:
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., save the file format as utf-8 format without BOM
Cause 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() - 返回输出缓冲区的内容 ob_flush() - 冲刷出(送出)输出缓冲区中的内容 ob_clean() - 清空(擦掉)输出缓冲区 ob_end_flush() - 冲刷出(送出)输出缓冲区内容并关闭缓冲 ob_end_clean() - 清空(擦除)缓冲区并关闭输出缓冲 flush() - 刷新输出缓冲
Judge whether the GD library is installed
function_exists('imagecreate') Judge get_extension_funcs() by judging whether the method provided by the extension library exists, but it is not comprehensive and this method is not recommended (because some extensions There is no function provided)
in_array('extension', get_loaded_extensions()) Determine whether the extension is installed by verifying whether it is in the loaded extension (comprehensive, but not concise)
extension_loade('Extension library name') Verify by judging whether the extension library is loaded (comprehensive and 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 should I do if PHP cannot display the picture using GD?. For more information, please follow other related articles on the PHP Chinese website!