繁体   English   中英

基于csv数据的php绘图

[英]php drawing based on csv data

我想做的是从csv文件中加载一些值,并将它们用作x,y值来绘制一些矩形。

我正在加载文件,但是不是显示图像,而是输出原始图像数据。 我知道在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);
}

?>

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

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

您可能想通过drawGraph返回图像本身来实现。 这样就像您最初显示的那样,然后确保使用header('Content-Type: image/png'); 或等同于您生成的内容。

如果要直接在浏览器中对其进行测试,则需要从示例中删除标记,然后将<?PHP include("parse.php"); ?> <?PHP include("parse.php"); ?>在php标记之外没有其他字符(如果您留下多余的空格或换行符,它将认为它是图像的一部分。

编辑:错过了循环问题。

请记住,您的drawGraph函数会在imagepng中创建并显示一个png,这意味着,如果您在示例中多次调用它,则将是单独的PNG图像,这些图像会融合在一起。 您可能想实例化图像,然后在循环中绘制矩形,然后最终输出图像。

//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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM