输出HTML标签时的图像内容类型会导致问题

时间:2011-11-02 02:05:45

标签: php

我有以下代码在我的php文件中完美运行并生成直方图图像。但是,只要我添加一个html标签,它就不会再生成直方图,而是一个空图像。在我看来,问题出在第一行header("Content-type: image/jpeg");。但我该如何解决呢?

<html>
    <?php
        // Send the PNG header information. Replace for JPEG or GIF or whatever
        header("Content-type: image/jpeg");

            // This array of values is just here for the example.
            $data = array('3400','2570','245','473','1000','3456','780');

            // Get the total value of columns we are going to plot
            $sum = array_sum($data);

            // Get the height and width of the final image
            $height = 255;
            $width = 320;

            $im = imagecreate($width,$height); // width , height px

            // Generate the image variables
            $white = imagecolorallocate($im,255,255,255); 
            $black = imagecolorallocate($im,0,0,0);   
            $red = imagecolorallocate($im,255,0,0);   


            imageline($im, 10, 5, 10, 230, $black);
            imageline($im, 10, 230, 300, 230, $black);

            // Now plot each column
            $x = 15;   
            $y = 230;   
            $x_width = 20;  
            $y_ht = 0; 

            for ($i=0;$i<7;$i++){

              $y_ht = ($data[$i]/$sum)* $height;    

                  // This part is just for 3D effect
              imagerectangle($im,$x,$y,$x+$x_width,($y-$y_ht),$red);
                  imagestring( $im,2,$x-1,$y+10,$data[$i],$black);

              $x += ($x_width+20);  

            }

            imagejpeg($im);

    ?> 
</html>

2 个答案:

答案 0 :(得分:4)

你需要两个脚本,一个生成带有<img src="...">的html的脚本,它引用生成图像的php文件......你不能直接在html中拥有图像。

答案 1 :(得分:0)

删除PHP文件中的标记,因为它不是HTML文档。 确保之前没有空间 <?php 打开标签。

标签内调用该文件,如

<img src="genrated.jpg.php" />