
Solution
1. Open the gd2 library and view it through phpinfo. Clear the BOM. The code is written starting from the top line, so the problem may occur in the code.
2. Add the ob_clean() statement before the header and then run it.
Note
When generating images, header('Content-type: image/png'); cannot have output in front. Or, add: ob_clean(); Even if you use output, you can use this sentence to clear the output cache.
Solve examples
//Set the verification code height and widthnumber of characters above
$img_w = 70;
$img_h = 22;
$font = 5;
$char_len = 5;
//Array merging, the range() function returns a range array
$char = array_merge ( range ( 'a', 'z' ), range ( 'A', 'Z' ), range ( '1', '9' ) );
$rand_keys = array_rand ( $char, $char_len ); // Randomly take a specified number of elements from the array to generate key values
if ($char_len == 1) { //If there is only one number, array_rand() returns a non-array type
$rand_keys = array ($rand_keys );
}
shuffle($rand_keys); //No need to use
$code = '';
foreach ( $rand_keys as $k ) {
$code .= $char [$k];
}
session_start ();
$_SESSION ['captcha'] = $code;
//Add line and color
//Create new image
$img = imagecreatetruecolor ( $img_w, $img_h );
//assign color
$bg_color = imagecolorallocate ( $img, 0xcc, 0xcc, 0xcc );
//Canvas background color
imagefill ( $img, 0, 0, $bg_color );
//interference line
for($i = 0; $i < 300; ++$i) {
$color = imagecolorallocate ( $img, mt_rand ( 0, 255 ), mt_rand ( 0, 255 ), mt_rand ( 0, 255 ) );
imagesetpixel ( $img, mt_rand ( 0, $img_w ), mt_rand ( 0, $img_h ), $color );
}
for($i = 0; $i <= 10; ++ $i) {
//Set the line color
$color = imageColorAllocate ( $img, mt_rand ( 0, 255 ), mt_rand ( 0, 255 ), mt_rand ( 0, 255 ) );
//Draw a straight line randomly on the $img image
imageline ( $img, mt_rand ( 0, $img_w ), mt_rand ( 0, $img_h ), mt_rand ( 0, $img_w ), mt_rand ( 0, $img_h ), $color );
//imagesetpixel($img,mt_rand(0,$img_w),mt_rand(0,$img_h),$color);
}
//Add frame
$rect_color = imagecolorallocate ( $img, 0x90, 0x90, 0x90 );
imagerectangle ( $img, 0, 0, $img_w - 1, $img_h - 1, $rect_color );
$str_color = imagecolorallocate ( $img, mt_rand ( 0, 100 ), mt_rand ( 0, 100 ), mt_rand ( 0, 100 ) );
$font_w = imagefontwidth ( $font );
$font_h = imagefontheight ( $font );
$str_len = $font_w * $char_len;
imagestring ( $img, $font, ($img_w - $str_len) / 2, ($img_h - $font_h) / 2, $code, $str_color );The above is the solution to the problem that php cannot generate images. I hope it will be helpful to everyone.