使用来自txt文件的坐标用php绘制线条

时间:2010-06-05 02:13:17

标签: php line draw

我的文件A2.txt的坐标为x1,y1,x2,y2,如下所示:

204 13 225 59  
225 59 226 84  
226 84 219 111  
219 111 244 192  
244 192 236 209   
236 209 254 223  
254 223 276 258 
276 258 237 337  

在我的php文件中我有那个代码。此代码应占用每一行并使用坐标从行绘制线。但是有些事情是错误的,因为什么都没画:/:

<?php
$plik = fopen("A2.txt", 'r') or die("blad otarcia");
while(!feof($plik))
{
   $l = fgets($plik,20);
   $k = explode(' ',$l);

   imageline ( $mapa , $k[0] , $k[1] , $k[2] , $k[3] , $kolor );
}
imagejpeg($mapa);
imagedestroy($mapa);
fclose($plik) ;
?>

如果我使用imagejpeg和imagedestroy而它只有第一行画。怎么做画每一行? 请帮助:)

1 个答案:

答案 0 :(得分:6)

非结构化,无清理或错误检查示例:

<?php
$plik = <<<EOD
204 13 225 59  
225 59 226 84  
226 84 219 111  
219 111 244 192  
244 192 236 209   
236 209 254 223  
254 223 276 258 
276 258 237 337  
EOD;

$plik = preg_replace('/\r\n?/', "\n", $plik);

$arr = explode("\n", $plik);
array_walk($arr,
    function (&$value, $key) {
        $value = explode(' ', $value);
    }
);

$minwidth = array_reduce($arr,
    function ($res, $val) { return min($res, $val[0], $val[2]); },
    PHP_INT_MAX);
$maxwidth = array_reduce($arr,
    function ($res, $val) { return max($res, $val[0], $val[2]); },
    (PHP_INT_MAX * -1) - 1);
$minheight = array_reduce($arr,
    function ($res, $val) { return min($res, $val[1], $val[3]); },
    PHP_INT_MAX);
$maxheight = array_reduce($arr,
    function ($res, $val) { return max($res, $val[1], $val[3]); },
    (PHP_INT_MAX * -1) - 1);


/* note: The image does not reflect the "+ 1"'s I added in a subsequent edit */
$mapa = imagecreatetruecolor($maxwidth - $minwidth + 1, $maxheight - $minheight + 1);
$kolor = imagecolorallocate($mapa, 100, 200, 50);

foreach ($arr as $k) {
    imageline($mapa,
        $k[0] - $minwidth,
        $k[1] - $minheight,
        $k[2] - $minwidth,
        $k[3] - $minheight, $kolor );
}
header("Content-type: image/png");
imagepng($mapa);

结果:

result of script