close

用PHP面對畫圖表的時候,總是會產生非常大的困擾

它不會像excel一樣,只要輸入X,Y就能畫出各種的曲線圖、大餅圖

雖然有很多高手有模組可以套用,利用Flash來達成類似的功能

但若遇到客製化的時候,要改那些模組可能就...........顯得力不從心

所以,只能轉個彎,利用PHP的繪圖模式來達成了

基本概念就是先準備有XY格線的底圖,在這底圖把曲線畫上去

ear.jpg 

因為是要畫上去的,所以每個位置對應的像素一定要設計好

這張圖是500X500,每個邊緣離座標格線40像素,所以左上角的座標起始點對應像素是(40,40)

Y軸的每一格的距離為30像素,總共有14格!X軸是每一格是60像素,起跟末的格是30像素

所以,整個座標圖的長寬是(420,420),右下角的座標是(460,460)

這樣精算是為了以後能把像素座標轉成我們實際輸入數據的座標

接下來進入PHP繪圖功能

先建立兩個檔案,img.php、draw.php

img.php裡面只要填入<img src="draw.php" />就好

draw.php是主要繪圖的檔案

內容如下:

header('Content-Type: image/jpeg');

// 載入背景圖片,跟程式同個目錄底下
$im = @imagecreatefromjpeg( '1.jpg' );
if(!$im) {
    /* 建立一個繪圖區域 */
    $im  = imagecreatetruecolor(150, 30);  //代表XY的尺寸,意義不明XD
    $bgc = imagecolorallocate($im, 255, 255, 255);
    $tc  = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    /* 錯誤訊息 */
    imagestring($im, 1, 5, 5, 'Error loading ' . '1.jpg' , $tc);
}

$color = imagecolorallocate( $im, 255,0 ,0  ); //線條顏色

//畫線 
imageline( $im,40 , 40, 250, 250, $color ); //畫直線函式
// 標出座標點
imagefilledellipse($im, 40, 40, 8,8, $color); //畫圓函式
// 點出最後一個座標點
imagefilledellipse($im, 250, 250, 8,8, $color);

imagejpeg($im);
imagedestroy($im);

這樣成果如下

ear2.jpg 

當然繪圖還有很多函式

imagearc (int im, int cx, int cy, int w, int h, int s, int e, int col) 畫弧線

imagefilledrectangle (int im, int x1, int y1, int x2, int y2, int col) 畫矩形

imagedashedline (int im, int x1, int y1, int x2, int y2, int col)畫虛線

imagesetthickness ( resource image, int thickness)設定線條粗細

等等....請自行查明

arrow
arrow
    全站熱搜

    痞子貓 發表在 痞客邦 留言(0) 人氣()