Creating an image using PHP may seem like a daunting task, but it is straightforward if you know what are you trying to draw using PHP’s GD library for images.

Pie Charts in PHP

Pie Chart

To create a pie chart in PHP, create a new file piechart.php as shown below.

<?php
$image_width = 400;
$image_height = 400;

$image = imageCreate($image_width, $image_height);

//Lets create some colors
$bg_color = ImageColorAllocate($image, 255, 255, 255);
$color1 = ImageColorAllocate($image, 154,185,153);
$color2 = ImageColorAllocate($image,252,206,170);
$color3 = ImageColorAllocate($image,244,131,125);
$color4 = ImageColorAllocate($image,235, 73,96);
$color5 = ImageColorAllocate($image,39,54,59);

ImageFilledArc($image, 200, 200, 200, 200, 0, 120, $color1, IMG_ARC_PIE);
ImageFilledArc($image, 200, 200, 200, 200, 120, 140, $color2, IMG_ARC_PIE);
ImageFilledArc($image, 200, 200, 200, 200, 140, 180, $color3, IMG_ARC_PIE);
ImageFilledArc($image, 200, 200, 200, 200, 180, 225, $color4, IMG_ARC_PIE);
ImageFilledArc($image, 200, 200, 200, 200, 225, 360, $color5, IMG_ARC_PIE);
ob_clean();
header ("Content-type: image/png");
ImagePng($image);
ImageDestroy($image);
?>

ImageFilledArc() is the method which creates individual arcs of the pie chart.

Its syntax is simple. First, you have to decide the size of the image, create an image using imageCreate() method. This method will create an empty image, to be used as a canvas for your pie chart.

ob_clean() method will make sure that your web browser renders a new image every time.

The syntax

ImageFilledArc($img, $center_x, $center_y, $arc_width, $arc_height, $start, $end, $color, IMG_ARC_PIE)

The Parameters

$img is used for creating the image size
$center_x sets the x-coordinate of the center of the pie chart
$center_y sets the y-coordinate of the center of the pie chart
$arc_width and $arc_height will set the arc width and height
$start set the starting point for angle
$end explains arc end angle
$color would identify the color created with imageColorAllocate() method
IMG_ARC_PIE will define how to fill the image

This function returns true on success and false otherwise.
header (“Content-type: image/png”) will define the header to display images.

Recommended Posts:

Last modified: March 16, 2019

Comments

Write a Reply or Comment

Your email address will not be published.