admin管理员组

文章数量:1621657

用imagejpeg()画不出图片,不是乱码就是红叉.

 

1.输出结果: 乱码

代码 < html >
< head >
</ head >
< body >
<? php
header ( " content-type: image/jpeg " );  // 设置http头部的类型
for ( $i = 0 ; $i < 4 ; $i ++ )
{
    
$rand .= dechex ( rand ( 1 , 15 ));  // 生成随机数
}
$image   =  imagecreatetruecolor( 100 , 30 );  // 生成图片
$color   =  imagecolorallocate( $image ,   255 , 255 , 255 );
imagestring(
$image , 6 , rand ( 0 , 65 ) , rand ( 0 , 15 ) , $rand , $color );  // 把随机数画进图片
imagejpeg( $image );
?>
</ body >
</ html >

原因: http头部的content-type已经被设置为image/jpeg,所以不支持html代码了.

解决方法: 把html的代码去掉.

 

2.输出结果: 红叉

代码
<? php
header ( " content-type: image/jpeg " );
for ( $i = 0 ; $i < 4 ; $i ++ )
{
    
$rand .= dechex ( rand ( 1 , 15 ));  // 生成随机数
}
$image   =  imagecreatetruecolor( 100 , 30 );  // 生成图片
$color   =  imagecolorallocate( $image ,   255 , 255 , 255 );
imagestring(
$image , 6 , rand ( 0 , 65 ) , rand ( 0 , 15 ) , $rand , $color );  // 把随机数画进图片
imagejpeg( $image );
?>

原因: "<?php"前面不能有字符,这里"<?php"上面有一行空行('\n')

解决方法: 去掉"<?php"上面的空行.

注意: "<?php"前面是不能有字符,所以即使不是空行而是空格,也会出红叉.

 

3.输出结果: 红叉

代码 <? php
header ( " content-type: image/jpeg " );
for ( $i = 0 ; $i < 4 ; $i ++ )
{
    
$rand .= dechex ( rand ( 1 , 15 ));  // 生成随机数
}
$image   =  imagecreatetruecolor( 100 , 30 );  // 生成图片
$color   =  imagecolorallocate( $image ,   255 , 255 , 255 );
imagestring(
$image , 6 , rand ( 0 , 65 ) , rand ( 0 , 15 ) , $rand , $color );  // 把随机数画进图片
imagejpeg( $image );
?>

原因: 被Notice消息扰乱了,这里$rand没有被预先定义就使用,虽然PHP允许,但会出Notice消息提示.

本来Notice消息应该是输出到页面的,但是这里content-type被设置为image/jpeg,所以显示不出来.

样例: 运行以下代码会得到"Notice: Undefined variable: rand in E:\Website\test.php on line 3"

<? php
for ( $i = 0 ; $i < 4 ; $i ++ )
    
$rand .= dechex ( rand ( 1 , 15 ));
echo ( $rand );
?>

解决方法: 在开头加一句"error_reporting(E_ALL ^ E_NOTICE);"(取消Notice提示)或者"$rand=NULL;"(预先定义变量)

 

4.最后得到运行通过的代码:

代码 <? php
header ( " content-type: image/jpeg " );
// error_reporting(E_ALL ^ E_NOTICE); //取消Notice消息提示
$rand = null //预先 定义了$rand变量就不会被Notice提示了
for ( $i = 0 ; $i < 4 ; $i ++ )
{
    
$rand .= dechex ( rand ( 1 , 15 ));  // 生成随机数
}
$image   =  imagecreatetruecolor( 100 , 30 );  // 生成图片
$color   =  imagecolorallocate( $image ,   255 , 255 , 255 );
imagestring(
$image , 6 , rand ( 0 , 65 ) , rand ( 0 , 15 ) , $rand , $color );  // 把随机数画进图片
imagejpeg( $image );
?>

 

转载于:https://wwwblogs/live41/archive/2010/07/02/1769754.html

本文标签: 解决方法原因图片imagejpeg