解決PHP生成校驗碼時“圖像因其本身有錯無法顯示”的錯誤

今天使用http://crazymud.iteye.com/blog/452293給出的代碼進行PHP生成校驗碼功能的實現,發現firefox一直提示“圖像.......因其本身有錯無法顯示”的問題,作者也提示了說“如果瀏覽器顯示“圖像XXX因其本身有錯無法顯示”,可儘量去掉文中空格”,但把代碼中所有空格都去掉了還是不能顯示檢驗圖片。於是深度google,大部分的解決方案也是將“<?”這句代碼前的空格回車一切都刪掉以防止有html輸出,但這根本解決不了我的問題,後來看到有人在Header("Content-type: p_w_picpath/PNG");這句代碼前使用ob_clean()清除輸出,結果一試之下果然成功。現將原http://crazymud.iteye.com/blog/452293作者的代碼修改後貼到下面,以備不時之需(使用方法參看原帖):

  1. <?php 
  2. session_start(); 
  3. session_register("login_check_number");   
  4. //先成生背景,再把生成的驗證碼放上去 
  5. $img_height=70;//先定義圖片的長、寬 
  6. $img_width=25; 
  7. $authnum=''
  8. //生產驗證碼字符 
  9. $ychar="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"
  10. $list=explode(",",$ychar); 
  11. for($i=0;$i<4;$i++){ 
  12.     $randnum=rand(0,35); 
  13.     $authnum.=$list[$randnum]; 
  14. //把驗證碼字符保存到session 
  15. $_SESSION["login_check_number"] = $authnum;   
  16.  
  17. $aimg = p_w_picpathcreate($img_height,$img_width);    //生成圖片 
  18. p_w_picpathcolorallocate($aimg, 255,255,255);            //圖片底色,ImageColorAllocate第1次定義顏色PHP就認爲是底色了 
  19. $black = p_w_picpathcolorallocate($aimg, 0,0,0);        //定義需要的黑色 
  20.  
  21. for ($i=1; $i<=100; $i++) { 
  22.     p_w_picpathstring($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"@",p_w_picpathcolorallocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255))); 
  23.  
  24. //爲了區別於背景,這裏的顏色不超過200,上面的不小於200 
  25. for ($i=0;$i<strlen($authnum);$i++){ 
  26.     p_w_picpathstring($aimg, mt_rand(3,5),$i*$img_height/4+mt_rand(2,7),mt_rand(1,$img_width/2-2), $authnum[$i],p_w_picpathcolorallocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200))); 
  27. p_w_picpathrectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//畫一個矩形 
  28. ob_clean();  //關鍵代碼,防止出現'圖像因其本身有錯無法顯示'的問題。
  29. Header("Content-type: p_w_picpath/PNG"); 
  30. ImagePNG($aimg);//生成png格式 
  31. ImageDestroy($aimg); 
  32. ?> 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章