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

Source: Internet
Author: User
Tags 0xc0 dashed line polyline strlen


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 in addition to the GD library. In addition to installing the GD library, additional libraries may be required in PHP, depending on which image formats you need to support. GD Library can be downloaded free of charge in http://www.boutell.com/gd/, different GD version support image format is not exactly the same, the latest version of the GD library support GIF, JPEG, PNG, WBMP, XBM and other formats of image files, It also supports some font libraries such as FreeType, Type 1, and so on. The functions in the GD library enable you to manipulate and process various points, lines, geometries, text, and colors, or you can create or read image files in multiple formats.



In PHP, the operation of the image through the GD library, are processed in memory first, after the operation is completed and then file flow mode, output to the browser or stored in the server's disk. Creating an image should complete the 4 basic steps shown below.



(1) Creating a canvas: All drawing designs need to be done on a background image, and the canvas is actually a temporary area in memory for storing 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: After the canvas is created, you can use the various image functions to set the color of the images, fill the canvas, Draw points, line segments, various geometries, and add text to the image.



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



(4) Releasing resources: After the image is exported, 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 image background color
  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 dividing line (dashed 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 + $ recHeight-, $ 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 ();


The effect chart is 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 summary!



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



PHP is not limited to exporting HTML text. PHP can also be used to dynamically output images by using the GD extension library, such as text buttons, validation codes, data statistics, and so on. Ha can easily edit the image, trying to deal with thumbnails and add watermarks for the image, and so on, with powerful image processing capabilities.



First of all, let's start with the GD library, and draw a simple graph with some steps:



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



$img =imagecreatetruecolor (100,100), where two parameters correspond to each other, the width and height of the image we create



2, set up some necessary "dye box"



In fact, we define some of the fill colors that will be used later, where 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 a few more colors that we need



3, fill the area color, can be simply understood as fills the picture the background color, utilizes the Imagefill function



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



4, drawing graphics, such as drawing a pie chart, what is required is the IMAGEFILLEDARC function



IMAGEFILLEDARC () parameters are relatively large, shaped like Imagefilledarc ($img, M, $i, 100,50,0,45, $red, Img_arc_pie);



Each of these represents a 0-45-point arc drawn on the red-color-character img image to draw a $i as the starting point.



5, we can also add some explanation questions, such as the level of adding a string, using Imagestring ($img, 1,20,40, "hello,world!", $red), said in the IMG image in 20 40 coordinates, write a red Hello, world! Words



6, is to tell the image output



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



Second, the image output to the browser, imagepng ($img);



Finally, destroy the picture, that is, to release the memory occupied by the image Imagedestroy (IMG);


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.