Home > Article > Backend Development > What should I do if php imagepng cannot be output?
php The solution to the problem that imagepng cannot be output: 1. Store the file in a BOM-free format; 2. Define the header and clear the cache area, with code such as "header ('Content-Type: image/png') ;".
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
php imagepng cannot be output. manage?
The problem that PHP ImagePng() cannot display the image output in the browser
Take the code that randomly generates the verification code as an example. If you want to successfully output the image to the browser, you must pay attention to two things. :
private function captcha(){ ob_clean(); session_start(); header ('Content-Type: image/png'); $image=imagecreatetruecolor(100, 30);//背景颜色为白色 $color=imagecolorallocate($image, 255, 255, 255); imagefill($image, 20, 20, $color); $code=''; for($i=0;$i<4;$i++){ $fontSize=8; $x=rand(5,10)+$i*100/4; $y=rand(5, 15); $data='ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789'; $string=substr($data,rand(0, strlen($data)),1); $code.=$string; $color=imagecolorallocate($image,rand(0,120), rand(0,120), rand(0,120)); imagestring($image, $fontSize, $x, $y, $string, $color); } $_SESSION['code']=$code;//存储在session里 for($i=0;$i<200;$i++){ $pointColor=imagecolorallocate($image, rand(100, 255), rand(100, 255), rand(100, 255)); imagesetpixel($image, rand(0, 100), rand(0, 30), $pointColor); } for($i=0;$i<2;$i++){ $linePoint=imagecolorallocate($image, rand(150, 255), rand(150, 255), rand(150, 255)); imageline($image, rand(10, 50), rand(10, 20), rand(80,90), rand(15, 25), $linePoint); } imagepng($image); imagedestroy($image); }
<img class="img" src="http://xxxx/captcha">
(1) Store the file in a BOM-free format
(2) Define the header and clear the cache area
header ('Content-Type: image/png'); ob_clean();
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What should I do if php imagepng cannot be output?. For more information, please follow other related articles on the PHP Chinese website!