2012-08-12 99 views
1

我想要做的是从csv文件加载一些值,并使用它们作为x,y值来绘制一些矩形。基于csv数据的php绘图

我正在加载文件,但不是显示图像,而是输出原始图像数据。我知道,在HTML代码中,我可以使用

<img scr="foo.php"></script> 

正确显示图像,但我不知道怎么用这个来绘制基于关闭数据的每一行的csv文件的多个矩形。请帮忙。

CSV代码

20,40,60,80 
50,100,150,175 

索引PHP代码

<html> 
    <body> 
     <?php 
      include("parse.php"); 
     ?> 
    </body> 
</html> 

解析PHP代码

<?php 

include("draw.php"); 

$file = fopen("data.csv", "r"); 
while (!feof($file)) { 
    $line = fgetcsv($file); 

     drawGraph($line[0], $line[1], $line[2], $line[3]); 

} 
fclose($file); 
?> 

拉伸PHP代码

<?php 

function drawGraph($xPos, $yPos, $xxPos, $yyPos) { 

//create a 200 x 200 canvas image 
$canvas = imagecreatetruecolor(200, 200); 

//set canvas background to white 
$white = imagecolorallocate($canvas, 255, 255, 255); 
imagefill($canvas, 0, 0, $white); 

//create colors 
$pink = imagecolorallocate($canvas, 255, 105, 180); 

//draw rectangles 
imagerectangle($canvas, $xPos, $yPos, $xxPos, $yyPos, $pink); 

//ERROR - following line displays raw data of image not the actural image 
imagepng($canvas); 

imagedestroy($canvas); 
} 

?> 
+0

我实际上并没有完全理解你,但也许这有助于:记住在推送原始数据之前做header('Content-Type:image/png')。 – 2012-08-12 00:56:41

+1

你可以发布产生的HTML吗? – SomeKittens 2012-08-12 00:58:33

+0

这是一些无头‰PNGIHDRÈÈ“HTML输出的:9E =IDATxœíÜÁ\t A0A;¤»t',Ò‰ëSÈÃA^ FAE /吨ýnclpμÇê¸'a '\t一个' \t一个 '\t一个' \t一个'\t一个' \t一个 '\t一个' \t一个 '\t一个' \t一个 '\t一个' \t一个 '\t一个' \t一个 '\t一个' \t一个 '\t一个' \t一个'‰COE÷qÑÿû¼-]Í \t sam user1334130 2012-08-12 01:26:48

回答

1

您需要传递一个Content-Type标题,告诉浏览器数据是图像。如果使用drawGraph函数执行此操作,则无论如何都将输出原始数据。

<html> 
    <body> 
      <?php 
       include("parse.php"); 
      ?> 
     </body> 
</html> 

您可能想要使用drawGraph返回到图像本身。像你最初展示的那样,然后确保使用 header('Content-Type: image/png'); 或等同于您正在生成的内容。

如果你想在浏览器中直接测试它,你需要从你的例子中删除标签,并且只需在之外放置其他字符(如果你留下额外的空格或换行符,它会认为它是你的形象

编辑:错过了循环问题

记住,你的drawGraph函数创建和imagepng这意味着,如果你把它多次在你的例子这将是单独的PNG显示一个PNG。所有的图像都在一起玩,你可能想要实例化图像,并在厕所中画出矩形p,然后输出图像。

//create a 200 x 200 canvas image 
$canvas = imagecreatetruecolor(200, 200); 

//set canvas background to white 
$white = imagecolorallocate($canvas, 255, 255, 255); 
imagefill($canvas, 0, 0, $white); 

//create colors 
$pink = imagecolorallocate($canvas, 255, 105, 180); 

$file = fopen("data.csv", "r"); 
while (!feof($file)) { 
    $line = fgetcsv($file); 

    //draw rectangles 
    imagerectangle($canvas, $line[0], $line[1], $line[2], $line[3], $pink); 

} 

fclose($file); 


/** finally output entire single png **/  
//ERROR - following line displays raw data of image not the actural image 
imagepng($canvas); 

imagedestroy($canvas); 
+0

我已经尝试了Content-Type:image/png的标题,但没有奏效。 – user1334130 2012-08-12 01:07:02

+0

你确定你已经删除了所有无关字符吗?这是字面上的教科书示例http://php.net/manual/en/function.imagepng.php – matthewnreid 2012-08-12 01:07:48

+0

好吧,我只是再次尝试添加标头到index.php文件。它仍然不起作用,但像以前一样,显示图像的“断开链接”图标。 – user1334130 2012-08-12 01:09:03