1

好的,所以我正在学习如何使用 PHP 的 GD 库来生成投票、图像等。问题是当使用该imagejpeg函数输出图像时,屏幕上什么都没有显示。对于这个练习,我在 HTML 论坛上输入文本,需要使用 GD 库将文本放在图像上,基本上是在图像上放置文本。这很简单,我只是不明白为什么我的图像不会显示。下面是 HTML 表单代码和 PHP 代码。

HTML 表单:

<html>
    <head> 
        <title> Create Buttons </title> 
    </head>
    <body>
        <form action ="button.php" method ="post">
            <p> Type button text here </p>
            <input type="text" name="button_text" size ="20" />
            <p> Choose button color: </p>
            <input type ="radio" name="color" value="red"> Red <br>
            <input type ="radio" name="color" value="green"> Green <br>
            <input type ="radio" name="color" value="blue"> Blue <br>
            <input type ="submit" value ="Create Button" />
        </form>    
    </body>
</html>

PHP代码:

<?php
Header('Content-type: image/jpeg');
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$button_text = $_POST['button_text']; var_dump($button_text);
$color = $_POST['color']; var_dump($color);
if(empty($color) || empty($button_text)) {
    echo " Could not create image - form not filled correctly";
    exit;
}
$path = $DOCUMENT_ROOT."/uploads/$color-button.jpg";
$im = imagecreatefromjpeg ($path);
$width_image = imagesx($im);
$height_image = imagesy($im);

$width_image_wo_margins = $width_image-(2*18);
$height_image_wo_margins = $width_image-(2*18);

$font_size = 33;
putenv('GDFONTPATH=C:\Windows\Fonts');

$fontname = getenv('GDFONTPATH') . '\comic.ttf';
if(!is_file($fontname)) {
    die( "Missing Font");
}

do {
    $font_size--;
    $bbox = imagettfbbox($font_size,0,$fontname,$button_text);
    $right_text = $bbox[2];
    $left_text = $bbox[0];
    $width_text  = $right_text -$left_text;
    $height_text = abs($bbox[7] - $bbox[1]);
}

while($font_size > 8 && ( $height_text > $height_image_wo_margins || $width_text > $width_image_wo_margins));

if ( $height_text > $height_image_wo_margins || $width_text > $width_image_wo_margins) {
    echo "Text given wil not fit on button.<br />";
} else {
    $text_y = $width_image/2.0 - $width_text/2.0;
    $text_x = $height_image/2.0 - $height_text/2.0;

    if($left_text < 0) {
        $text_x += abs($left_text); //add factor for left overhang.  
    }
    $above_line_text = abs($bbox[7]);
    $text_y += $above_line_text;
    $text_y -=2;
    $white = imagecolorallocate($im,255,255,255);
    imagettftext($im, $font_size, 0, $text_x, $text_y, $white, $fontname, $button_text);

    imagejpeg($im, NULL,75); 
}
imagedestroy($im);
?>
4

3 回答 3

0

它没有显示,因为您实际上没有做任何事情来显示图像。当这个脚本创建一个图像时,你需要另一个来实际调用它,就像在普通 HTML 中一样。

该主题之前已在 SO 上介绍过:PHP GD 库:在同一页面上输出图像和文本

我还建议您完成一两个教程。如果您进行快速搜索,有几十个可用。我不会冒着把它变成“20 个伟大的 GD 教程”的风险在这里发布任何内容。

于 2012-12-16T02:58:19.373 回答
0

使用对我有用的 header('Content-Type: image/jpeg') 时删除 echo 语句

于 2012-12-16T03:04:22.917 回答
0

你的问题是var_dump陈述。

那就是将文本发送到您的输出。该imagejpeg()调用可能会很好地创建图像,但它不会与var_dump语句一起呈现。

于 2012-12-16T03:49:00.157 回答