
解決辦法
1.開啟gd2函式庫,透過phpinfo進行查看。清除bom,程式碼是頂行開始寫的,所以問題可能出現在程式碼上。
2.在header前面加上ob_clean()語句,隨後就可以運作了。
注意點
產生圖片時,header('Content-type: image/png');前面不能有輸出。或者,前面加:ob_clean(); 即使用輸出也可以透過這句話來清除輸出快取。
解決實例
//設定 驗證碼高度寬度上面字元個數
$img_w = 70;
$img_h = 22;
$font = 5;
$char_len = 5;
//數組合併, range()函數傳回一個範圍數組
$char = array_merge ( range ( 'a', 'z' ), range ( 'A', 'Z' ), range ( '1', '9' ) );
$rand_keys = array_rand ( $char, $char_len ); //隨機從陣列中取指定個數的元素,產生鍵值
if ($char_len == 1) { //若只有一個數,則array_rand()傳回非數組類型
$rand_keys = array ($rand_keys );
}
shuffle($rand_keys); //可以不用
$code = '';
foreach ( $rand_keys as $k ) {
$code .= $char [$k];
}
session_start ();
$_SESSION ['captcha'] = $code;
//新增線、色
//建立新圖片
$img = imagecreatetruecolor ( $img_w, $img_h );
//分配顏色
$bg_color = imagecolorallocate ( $img, 0xcc, 0xcc, 0xcc );
//畫布背景色
imagefill ( $img, 0, 0, $bg_color );
//幹擾線
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) {
//設定直線顏色
$color = imageColorAllocate ( $img, mt_rand ( 0, 255 ), mt_rand ( 0, 255 ), mt_rand ( 0, 255 ) );
//在$img圖片上隨機畫一條直線
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);
}
//加加框
$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 );以上就是php不能產生圖片的解決方法,希望對大家有幫助。