Using the GD Library in PHP to draw a line chart to draw a chart

Source: Internet
Author: User
Tags 0xc0 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 http://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 the image
  private $ title; // define the title
  private $ ydata; // define Y axis data
  private $ xdata; // define X axis data
  private $ seriesName; // define the name of each series data
  private $ color; // define bar chart color
  private $ bgcolor; // define the background color of the image
  private $ width; // define the width of the image
  private $ height; // define the length of the image
  / *
  * Constructor 
  * String title Picture title
  * Array xdata indexed 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 color array, the element value is '#DC'
  * /
  function setBarColor ($ color) {
   $ this-> color = $ color;
  }
 / *
  * Draw a line chart
  * /
  public function paintLineChart () {
   $ ydataNum = $ this-> arrayNum ($ this-> ydata); // Get the number of data groups
   $ max = $ this-> arrayMax ($ this-> ydata); // Get the maximum value of all rendered data
   $ max = ($ max>)? $ max:;
   $ multi = $ max /; // if the maximum data is greater than the size
   $ barHeightMulti =.; // bar scaling height
   $ lineWidth =;
   $ chartLeft = (+ strlen ($ max)) *; // set margin on the left of the picture
   $ lineY =; // Initialize the Y coordinate of the bar chart
   // Set the width and height of the picture
   // $ this-> width = $ lineWidth * count ($ this-> xdata) + $ chartLeft-$ lineWidth / .;
   $ margin =; // small rectangle describes the right margin
   $ recWidth =; // width of small rectangle
   $ recHeight =; // height of small rectangle
   $ space =; // space between small rectangle and bar chart
   $ tmpWidth =;
   // Set the width and height of the picture
   $ lineChartWidth = $ lineWidth * count ($ this-> xdata) + $ chartLeft-$ lineWidth / .;
   // Above two series of data plus the width of the small rectangle
   if ($ ydataNum>) {
    $ tmpWidth = $ this-> arrayLengthMax ($ this-> seriesName) ** / + $ space + $ recWidth + + $ margin;
   }
   $ this-> width = $ lineChartWidth + $ tmpWidth;
   $ this-> height =;
   $ this-> image = imagecreatetruecolor ($ this-> width, $ this-> height); // prepare the canvas
   $ this-> bgcolor = imagecolorallocate ($ this-> image ,,,); // background color of the image
   // Set 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 line color, font color, font path
   $ lineColor = imagecolorallocate ($ this-> image, xcc, xcc, xcc);
   $ fontColor = imagecolorallocate ($ this-> image, x, xf, xf);
   $ fontPath = 'font / simsun.ttc';
   imagefill ($ this-> image ,,, $ this-> bgcolor); // painting background
   // The drawing is divided into short lines and left and right edges
   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 the divider (dotted line) of the line chart
   foreach ($ this-> xdata as $ key => $ val) {
     $ lineX = $ chartLeft + + $ lineWidth * $ key;
     imageline ($ this-> image, $ lineX ,, $ lineX, $ lineY, IMG_COLOR_STYLED);
   }
   // polyline drawing
   foreach ($ this-> ydata as $ key => $ val) {
    if ($ ydataNum ==) {
     // When a series of data
     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 ,,, $ color []);
     }
     imageline ($ this-> image, $ lineX, $ lineY- $ barHeightMulti * $ val / $ multi, $ lineX + $ lineWidth, $ lineY, $ color []);
     imagefilledellipse ($ this-> image, $ lineX, $ lineY- $ barHeightMulti * $ val / $ multi ,,, $ color []);
    } elseif ($ ydataNum>) {
     // When data of multiple series
     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 chart
   foreach ($ this-> xdata as $ key => $ val) {
    $ lineX = $ chartLeft + $ lineWidth * $ key + $ lineWidth /-;
    imagettftext ($ this-> image ,,-, $ lineX, $ lineY +, $ fontColor, $ fontPath, $ this-> xdata [$ key]);
   }
   // Draw a small rectangle when the two series of data are above and 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 + $ r
ecHeight-, $ fontColor, $ fontPath, $ this-> seriesName [$ key]);
     $ y + = $ recHeight +;
    }
   }
   // drawing 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 binary array, statistics the length of the array
  * Array arr
  * /
  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 to calculate the depth of the array
  * Array arr
  * /
  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 to find the largest value in a group
  * Array arr
  * /
  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, average the array
  * Array arr
  * /
  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, find the largest element length in the array
  * Array arr string array, must be Chinese characters
  * /
  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 = imagecolorallocate ($ 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;

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.