Using the GD Library in PHP to draw a line chart drawing method _php Example

Source: Internet
Author: User
Tags 0xc0 dashed line polyline
This article through the code to introduce the use of the GD Library in PHP to draw a line chart, which involves some simple use of the GD library in PHP, this article introduces very detailed, interested friends learn together

In PHP, there are some simple image functions can be used directly, but most of the images to be processed, you need to compile PHP with the GD library. In addition to installing the GD library, additional libraries may be required in PHP, depending on which image format you need to support. GD Library can be downloaded in hhttp://www.boutell.com/gd/free, different GD version support image format is not exactly the same, the latest GD library version supports GIF, JPEG, PNG, WBMP, XBM and other formats of image files, also supports some font libraries such as FreeType, Type 1. Functions in the GD library can be used to manipulate and manipulate various points, lines, geometries, text and colors, or to create or read image files in multiple formats.

In PHP, the operation of the image through the GD library is processed in memory first, and the operation is then streamed to the browser or stored on the server's disk. Creating an image should complete the 4 basic steps shown below.

(1) Create a canvas: All drawing designs need to be done on a background image, and the canvas is actually a temporary area in memory that is used to store information about the image. Future image operations will be based on this background canvas, which is managed similar to the canvas we use when drawing.

(2) Drawing the image: Once the canvas is created, you can use this canvas resource to set the color of the image, fill the canvas, Draw points, segment, various geometries, and add text to the image using various portrait functions.

(3) Output Image: After the entire image is drawn, the image needs to be saved in some format to the file specified by the server, or the image will be printed directly to the user on the browser. However, before the image output, be sure to use the header () function to send the CONTENT-TYPE notification browser, this time sending a picture is not text.

(4) Releasing resources: After the image is output, the contents of the canvas are no longer useful. For the sake of saving system resources, it is necessary to clear all the memory resources occupied by the canvas in time.

In PHP, use GD to draw a line chart with the following code:

Class chart{private $image;//define image private $title;//define title private $ydata;//define y-axis data private $xdata;//define x-axis data priv Ate $seriesName; Define the name of each series of data private $color; Define a bar chart color private $bgcolor; Define picture background color private $width; Defines the wide private $height of the picture; Define the LONG/* * constructor for the picture * String Title * The image title * Array XData Index array, x-axis data * Array Ydata index array, numeric array, y-axis data * Array Series_name Index   Array, data series name */function __construct ($title, $xdata, $ydata, $seriesName) {$this->title = $title;   $this->xdata = $xdata;   $this->ydata = $ydata;   $this->seriesname = $seriesName;  $this->color = Array (' #DC ', ' #B ', ' #EDB ', ' #DDDF ', ' #CBE ', ' #E ', ' #FF ', ' #FFF ', ' #AFC ');  }/* Public method, set the color of the bar chart * Array color arrays, the element value is ' #DC ' this form */function Setbarcolor ($color) {$this->color = $color; }/* * Draw a line chart */Public Function Paintlinechart () {$ydataNum = $this->arraynum ($this->ydata);//Get the number of data groupings $ max = $this->arraymax ($this->ydata); Gets the maximum value of all rendered data $max = ($max >)? $max:; $multi = $max/; If the maximum data is greater than the shrink processing $barHeightMulti =.;   The scale of the bar high scale $lineWidth =; $chartLeft = (+strlen ($max)) *; Set margin $lineY to the left of the picture =;    Initialize the coordinates of y of the bar chart//Set the picture width, height//$this->width = $lineWidth *count ($this->xdata) + $chartLeft-$lineWidth/.; $margin =; The small rectangle describes the right margin $recWidth =; Width $recHeight of small rectangles =; High $space of small rectangles =;   The spacing between small rectangles and bar graphs $tmpWidth =; Set the width and height of the picture $lineChartWidth = $lineWidth *count ($this->xdata) + $chartLeft-$lineWidth/.   ; Two series data above plus a small rectangular width if ($ydataNum >) {$tmpWidth = $this->arraylengthmax ($this->seriesname) **/+ $space + $r   Ecwidth + + $margin;    } $this->width = $lineChartWidth + $tmpWidth;    $this->height =; $this->image = Imagecreatetruecolor ($this->width, $this->height); Prepare the canvas $this->bgcolor = imagecolorallocate ($this->image,,,);   The background color of the picture//Setting the color of the bar chart $color = Array ();    foreach ($this->color as $col) {$col = substr ($col, strlen ($col)-); $red= Hexdec (substr ($col,,));    $green = Hexdec (substr ($col,,));    $blue = Hexdec (substr ($col,,));   $color [] = Imagecolorallocate ($this->image, $red, $green, $blue);   }//Set the color of the segment, the color of the font, the path to the font $lineColor = Imagecolorallocate ($this->image, XCC,XCC,XCC);   $fontColor = Imagecolorallocate ($this->image, X,XF,XF);   $fontPath = ' FONT/SIMSUN.TTC '; Imagefill ($this->image,,, $this->bgcolor); Drawing background//Draw the short line with left and right edge for ($i =; $i <; $i + +) {imageline ($this->image, $chartLeft-, $lineY-$barHeightMulti *    $max//$multi * $i, $lineChartWidth, $lineY-$barHeightMulti * $max//$multi * $i, $lineColor);   Imagestring ($this->image,,, $lineY-$barHeightMulti * $max//$multi * $i-,floor ($max/* $i), $fontColor);   } imageline ($this->image, $chartLeft-,, $chartLeft-, $lineY, $lineColor);   Imageline ($this->image, $lineChartWidth-,, $lineChartWidth-, $lineY, $lineColor); $style = Array ($lineColor, $lineColor, $lineColor, $lineColor, $lineColor, $this->bgcolor, $this->bgcolor, $this- >bgcolOr, $this->bgcolor, $this->bgcolor);   Imagesetstyle ($this->image, $style);     Draw a line chart divider (dashed line) foreach ($this->xdata as $key = + $val) {$lineX = $chartLeft + + $lineWidth * $key;   Imageline ($this->image, $lineX,, $lineX, $lineY, img_color_styled); }//Sketched polyline foreach ($this->ydata as $key + = $val) {if ($ydataNum = =) {//a series of data when if ($key = = COUNT ($     This->ydata)-) break;     $lineX = $chartLeft + + $lineWidth * $key;     $lineY = $lineY-$barHeightMulti * ($this->ydata[$key +])/$multi; Draw Polyline if ($key = = count ($this->ydata)-) {Imagefilledellipse ($this->image, $lineX + $lineWidth, $lineY-,,, $col     Or[]);     } imageline ($this->image, $lineX, $lineY-$barHeightMulti * $val/$multi, $lineX + $lineWidth, $lineY, $color []);    Imagefilledellipse ($this->image, $lineX, $lineY-$barHeightMulti * $val/$multi,,, $color []); }elseif ($ydataNum >) {//Multiple series of data when foreach ($val as $ckey = + $cval) {if ($ckey = = count ($val)-) break   ;    $lineX = $chartLeft + + $lineWidth * $CKEY;      $lineY = $lineY-$barHeightMulti * ($val [$ckey +])/$multi; Draw Polyline if ($ckey = = count ($val)-) {Imagefilledellipse ($this->image, $lineX + $lineWidth, $lineY,,, $color [$key%      Count ($this->color)]); } imageline ($this->image, $lineX, $lineY-$barHeightMulti * $cval/$multi, $lineX + $lineWidth, $lineY, $color [$key%      Count ($this->color)]); Imagefilledellipse ($this->image, $lineX, $lineY-$barHeightMulti * $cval/$multi,,, $color [$key%count ($this     color)]); }}}//The value of the x-coordinate of the drawing bar is foreach ($this->xdata as $key + = $val) {$lineX = $chartLeft + $lineWidth * $key + $li    newidth/-;   Imagettftext ($this->image,,-, $lineX, $lineY +, $fontColor, $fontPath, $this->xdata[$key]);    }//Two series data above when drawing a small rectangle and then the text description if ($ydataNum >) {$x = $lineChartWidth + $space;    $y =; foreach ($this->seriesname as $key = + $val) {imagefilledrectangle ($this->image, $x, $y, $x + $recWidth, $y +$ Recheight, $color [$key%count ($this->color)]);     Imagettftext ($this->image,,, $x + $recWidth +, $y + $recHeight-, $fontColor, $fontPath, $this->seriesname[$key]);       $y + = $recHeight +;   }}//painting title $titleStart = ($this->width-. *strlen ($this->title))/;   Imagettftext ($this->image,,, $titleStart, $fontColor, $fontPath, $this->title);   Output image Header ("Content-type:image/png");  Imagepng ($this->image);   }/* Private method, when the array is a two-tuple array, the length of the statistic array * Array arr to do the statistics of the arrays */Private Function Arraynum ($arr) {$num =;    if (Is_array ($arr)) {$num + +;      for ($i =; $i < count ($arr), $i + +) {if (Is_array ($arr [$i])) {$num = count ($arr);     Break  }}} return $num;   }/* Private method, calculation of the depth of the array * Array arr arrays */Private Function arraydepth ($arr) {$num =;    if (Is_array ($arr)) {$num + +;      for ($i =; $i < count ($arr), $i + +) {if (Is_array ($arr [$i])) {$num + = $this->arraydepth ($arr [$i]);     Break  }}} return $num; }/* Private method, find a group of the mostLarge value * Array arr digital array */Private Function ArrayMax ($arr) {$depth = $this->arraydepth ($arr);   $max =;    if ($depth = =) {Rsort ($arr);     $max = $arr [];       }elseif ($depth >) {foreach ($arr as $val) {if (Is_array ($val)) {if ($this->arraymax ($val) > $max) {      $max = $this->arraymax ($val);      }}else{if ($val > $max) {$max = $val;  }}}} return $max;   }/* Private method, the average of an array of arrays arr array */function Arrayaver ($arr) {$aver = array ();    foreach ($arr as $val) {if (Is_array ($val)) {$aver = Array_merge ($aver, $val);    }else{$aver [] = $val;  }} return Array_sum ($aver)/count ($aver);   }/* Private method, the largest value of the element length in the array * array arr string arrays, must be kanji */private Function Arraylengthmax ($arr) {$length =;   foreach ($arr as $val) {$length = strlen ($val) > $length strlen ($val): $length;  } return $length/;  }//destructor function __destruct () {Imagedestroy ($this->image); } }

The test code is as follows:

$xdata = Array (' Test one ', ' Test two ', ' Test three ', ' Test Four ', ' Test Five ', ' Test Six ', ' Test seven ', ' Test Eight ', ' Test Nine '); $ydata = Array (Array (,,,,,,,,), Array (,,,,,,,,)); $color = Array (); $seriesName = Array ("July", "August"); $title = "test Data"; $IMG = new Chart ($title, $xdata, $ydata, $seriesName); $IMG->paintlinechart ();

As follows:


To the end of this code.

Here are some simple uses of the GD library in PHP

Today understand some of the simple use of GD library, now a little to summarize!

What is the GD library? , graphic device, Image tool Library, GD Library is an extension of PHP processing graphics, the GD library provides a series of APIs to handle images, use the GD library to process images, or create images. The GD library on the site is often used to generate thumbnails or to add watermarks to images or generate reports on site data.

PHP is not limited to outputting HTML text. PHP can also be used to dynamically output images, such as text buttons, verification codes, data charts, etc. by using the GD extension library. Ha can easily edit images, try to handle thumbnails and add watermarks to images, etc., with powerful image processing capabilities.

First of all, let's say a few steps of the GD library to draw a simple graph:

1, the first is to create a canvas, here we use the Imagecreatetruecolor function, you can also use imagecreate, the difference is that the former creates a true color image, the latter created a color palette-based image

$img =imagecreatetruecolor (100,100), of which two parameters correspond, the width and height of the image we created

2, set up some necessary "dye box"

is actually defining some of the fill colors that will be used later, and here we are uniformly defined in this position, where we use the Imagecolorallocate function

$white =imagecolorallocate ($img, 0xff,0xff,0xff) or you can use RGB color naming methods such as $white=imagecolorallocate ($img, 255,255,255); $ Gray = Imagecolorallocate ($img, 0xC0, 0xC0, 0xC0); $darkgray = Imagecolorallocate ($img, 0x90, 0x90, 0x90); $navy = Imagecolo Rallocate ($img, 0x00, 0x00, 0x80), $darknavy = Imagecolorallocate ($img, 0x00, 0x00, 0x50); $red = Imagecolorallocate ($img, 0xFF, 0x00, 0x00); $darkred = Imagecolorallocate ($img, 0x90, 0x00, 0x00); $black =imagecolorallocate ($img, 0x00,0x00,0x00 );

Here we define more of the required colors

3, fill area color, can be easily understood as the background color of the fill picture, using the Imagefill function

Imagefill ($img, 0,0, $white), where 0 0 indicates that the background color is filled starting at coordinates x y

4, draw the graph, for example to draw the pie chart, need is Imagefilledarc function

The parameters of Imagefilledarc () are relatively more, shaped like Imagefilledarc ($img, $red, $i, 100,50,0,45, Img_arc_pie);

It is represented by the red color word img image on the drawing of a $i as a starting point, with 0 45 angle to draw an arc in this range

5, during the period we can also add a few explanatory questions, such as adding a string horizontally, using imagestring ($img, 1,20,40, "hello,world!", $red), in the IMG image with 20 40 as the coordinates, write a red Hello, world! Words

6, is to speak the image output

The first thing to tell is which image format the browser will output, such as PNG output, using the header ("Content-type:image/png");

Next, the picture is exported to the browser, imagepng ($img);

Finally, destroy the image, i.e. release the Memory Imagedestroy (IMG) occupied by the picture storage;

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.