Using PHP GD Library for Image Processing and JpGraph Chart Generation

This article explains how to use PHP's GD extension and the JpGraph library to create, manipulate, and output images—including canvases, colors, text, CAPTCHA generation, watermarking, and statistical charts—while providing complete code examples and configuration steps.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP GD Library for Image Processing and JpGraph Chart Generation

1. GD2

1.1 What is GD2?

PHP can use the GD extension to dynamically generate and manipulate images. GD (also called GD2) is an open‑source C‑based graphics library available to PHP, Perl and other languages, providing APIs for creating, editing and adding watermarks to pictures.

1.2 What can GD2 do?

With GD you can draw graphics, generate charts (especially when combined with Ajax), and create verification code images (CAPTCHA) directly in web pages.

1.3 Loading GD2

Different PHP versions configure GD differently; for PHP 7.2+ the directive is extension=gd2. You can verify the extension via php.ini, phpinfo (e.g., http://localhost/?phpinfo=-1) or the gd_info() function.

2. Common Image Operations

Image processing in PHP follows four steps: create a canvas in memory, draw on it, output the image (to browser or file), and free the resources.

Create canvas: use imagecreate() or imagecreatetruecolor() to allocate a temporary image area.

Draw: set colors, draw shapes, text, etc.

Output: send appropriate Content‑type header and use functions such as imagejpeg(), imagepng(), imagegif().

Free: call imagedestroy() to release memory.

2.1 Creating a Canvas

Use imagecreate($x, $y) for a palette‑based image or imagecreatetruecolor($width, $height) for a true‑color image. Example:

<?php
    $img = @imagecreatetruecolor(120, 120) or die('Canvas creation failed!');
    echo 'Canvas width: '.imagesx($img).' pixels';
    echo '<br>Canvas height: '.imagesy($img).' pixels';
?>

Other functions such as imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), and imagecreatefromwbmp() can load images from files or URLs.

2.2 Defining Colors

Use imagecolorallocate() for opaque colors and imagecolorallocatealpha() for colors with transparency (alpha 0 = opaque, 127 = fully transparent).

2.3 Drawing Text

Functions like imagestring(), imagestringup(), imagechar(), imagecharup(), and imagettftext() allow drawing text in various orientations and fonts.

2.4 Outputting Images

Use imagegif(), imagejpeg(), or imagepng() to send the image to the browser or save it to a file.

2.5 Releasing Resources

Call imagedestroy($image) after you are done.

3. Application Examples

3.1 Generating a CAPTCHA

Steps: create canvas, draw random characters, add noise, output, and free resources. Example code:

<?php
function rand_str($length) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str = '';
    for($i=0;$i<$length;$i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}
function rand_color($image) {
    return imagecolorallocate($image, rand(127,255), rand(127,255), rand(127,255));
}
$image = imagecreate(200,100);
imagecolorallocate($image,0,0,0);
for($i=0;$i<=9;$i++) {
    imageline($image, rand(0,200), rand(0,100), rand(0,200), rand(0,100), rand_color($image));
}
for($i=0;$i<=100;$i++) {
    imagesetpixel($image, rand(0,200), rand(0,100), rand_color($image));
}
$length = 4;
$str = rand_str($length);
$font = 'C:\\Windows\\Fonts\\simhei.ttf';
for($i=0;$i<$length;$i++) {
    imagettftext($image, rand(20,38), rand(0,60), $i*50+25, rand(30,70), rand_color($image), $font, $str[$i]);
}
header('Content-type:image/jpeg');
imagejpeg($image);
imagedestroy($image);
?>

3.2 Adding a Watermark

Use imagecopy() to overlay a watermark image onto a source image. Example function watermark($img,$watermark,$district=0,$quality=95) handles positioning, format detection, and saving the result.

<?php
function watermark($img,$watermark,$district=0,$watermarkquality=95) {
    $imginfo = @getimagesize($img);
    $watermarkinfo = @getimagesize($watermark);
    $img_w = $imginfo[0]; $img_h = $imginfo[1];
    $watermark_w = $watermarkinfo[0]; $watermark_h = $watermarkinfo[1];
    if($district==0) $district = rand(1,9);
    if(!is_int($district) || $district<1 || $district>9) $district = 9;
    // calculate $x,$y based on $district ...
    // load source and watermark based on type
    // copy and save
}
$file = './back.gif';
$water = './logo.png';
watermark($file,$water);
?>

4. JpGraph

JpGraph is a PHP library built on GD2 for creating complex statistical charts. It supports PHP 5 and PHP 7 and requires GD.

4.1 Introduction

JpGraph provides classes for bar, line, pie, and 3D pie charts with a simple API.

4.2 Installation

Download from the official site, copy the src directory into your project, and add the directory to include_path in php.ini, then restart Apache.

4.3 Configuration

Adjust CHINESE_TTF_FONT and DEFAULT_GFORMAT in the configuration files to set font and default image format.

4.4 Creating a Chart

Typical steps: include required classes, prepare data, instantiate Graph, set titles, axes, create plot objects (e.g., BarPlot), add them to the graph, and call Stroke() to render.

<?php
include_once "./src/jpgraph.php";
include_once "./src/jpgraph_bar.php";
$datay = array(190,188,223,289,305,488,489,408,299,566,187,105);
$graph = new Graph(600,300,"auto");
$graph->setScale("textlin");
$graph->yaxis->scale->SetGrace(20);
$graph->SetShadow();
$graph->img->setMargin(40,30,30,40);
$bplot = new BarPlot($datay);
$bplot->SetFillcolor('orange');
$graph->Add($bplot);
$bplot->value->Show();
$bplot->value->SetFormat('%d');
$graph->SetMarginColor("lightblue");
$graph->title->Set(iconv('utf-8','gb2312','JpGraph Demo'));
$a = array("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");
foreach($a as $k=>$v){ $a[$k]=iconv('utf-8','gb2312',$v); }
$graph->xaxis->SetTickLabels($a);
$graph->title->SetFont(FF_SIMSUN);
$graph->xaxis->SetFont(FF_SIMSUN);
$graph->Stroke();
?>

Note: JpGraph assumes GB2312 encoding for Chinese characters; use iconv() to convert UTF‑8 strings when necessary.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Image ProcessingWatermarkCaptchaPHPGD libraryJpGraph
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.