在PHP中使用imagejpeg生成图像

时间:2012-06-14 16:47:10

标签: php image

我不知道我在哪里犯了一个错误,当我从http://localhost/image.php?application=first的代码中解雇时,一切正常。

session_start();
$name = $_GET['application'];   

$text = rand(10000,99999); 
$_SESSION['application'][$name] = $text;

$height = 25; 
$width = 65; 
$image_p = imagecreate($width, $height); 
$black = imagecolorallocate($image_p, 0, 0, 0); 
$white = imagecolorallocate($image_p, 255, 255, 255); 
$font_size = 14; 

imagestring($image_p, $font_size, 5, 5, $text, $white); 
imagejpeg($image_p, null, 80);

但是我改变了这个

的代码
if (isset($_GET['application']) && !empty($_GET['application'])) {
    if (isset($_GET['image']) && $_GET['image'] == 'get'){
    session_start();
    $name = $_GET['application'];   

    $text = rand(10000,99999); 
    $_SESSION['application'][$name] = $text;

    $height = 25; 
    $width = 65; 
    $image_p = imagecreate($width, $height); 
    $black = imagecolorallocate($image_p, 0, 0, 0); 
    $white = imagecolorallocate($image_p, 255, 255, 255); 
    $font_size = 14;
    imagestring($image_p, $font_size, 5, 5, $text, $white); 

    imagejpeg($image_p, null, 80);
}
}

然后我在浏览器中获得RAW格式,所以我添加

header('Content-type: image/jpeg'); 
imagejpeg($image_p, null, 80);

到代码,现在我收到消息,我的图片被中断,但当我将它保存在驱动器上并从IrfanView启动时,它正常打开。

我想补充说我正在测试ob_start()函数,但它没有改变任何内容。

2 个答案:

答案 0 :(得分:2)

点击此网址时,对我来说很有用:

http://localhost/image.php?application=first&image=get

以下是我在image.php中使用的确切代码:     

if (isset($_GET['application']) && !empty($_GET['application'])) {
    if (isset($_GET['image']) && $_GET['image'] == 'get'){
        session_start();
        $name = $_GET['application'];   

        $text = rand(10000,99999); 
        $_SESSION['application'][$name] = $text;

        $height = 25; 
        $width = 65; 
        $image_p = imagecreate($width, $height); 
        $black = imagecolorallocate($image_p, 0, 0, 0); 
        $white = imagecolorallocate($image_p, 255, 255, 255); 
        $font_size = 14;
        imagestring($image_p, $font_size, 5, 5, $text, $white); 

        header('Content-type: image/jpeg');
        imagejpeg($image_p, null, 80);
    }
}

?>

答案 1 :(得分:0)

好吧我明白了。问题是我在主IF声明之前添加了require 'common.php'。我的整个代码都是这样的

<?php
require 'common.php';
    if (isset($_GET['application']) && !empty($_GET['application'])) {
    if (isset($_GET['image']) && $_GET['image'] == 'get'){
        session_start();
        $name = $_GET['application'];                   $text = rand(10000,99999);             $_SESSION['application'][$name] = $text;
            $height = 25;             $width = 65;             $image_p = imagecreate($width, $height);             $black = imagecolorallocate($image_p, 0, 0, 0);             $white = imagecolorallocate($image_p, 255, 255, 255);             $font_size = 14;
        imagestring($image_p, $font_size, 5, 5, $text, $white);                 header('Content-type: image/jpeg');
        imagejpeg($image_p, null, 80);
    }
.
.
.

所以当我搬到其他地方时,everythig很棒! 谢谢伙伴们的帮助! :)