2012-08-12 92 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