How to manipulate images and work with GD library in php

How to manipulate images and work with GD library in PHP

Graphics are used to make a website more beautiful and you can use many tools like Adobe Photoshop for that but in a lot of places, we need dynamic image manipulation. For this purpose, we can use GD library in PHP. In this article, you will learn how to manipulate images and work with GD library in PHP. You can open, save or draw images on a canvas, create a thumbnail of a large image or can add watermark and many other effects.

manipluting image using php gd library

Colors theory and coordinate system

Before working in GD library let us explore colors theory and coordinate system. The computer is the world of colors. As you have seen many color monitors. The computer uses a Color Theory Model that is called RGB or red, green, blue. A computer creates colors by using these basic colors.

Co-ordinate System

For drawing images on a canvas you have to understand the coordinate system. Canvas is an area where we do all drawing, it has some start and end points. If you are familiar with the mathematical graph that has x and y coordinates with horizontal axis as x and y as the vertical axis and a line is drawn from bottom right to upwards right.
 math coodinate system
PHP co-ordinate system starts from top, left as shown in image
php gd library coordinate system
First pixel position is 0,0 on the top left. If we have a 200 X 300 pixels wide canvas, then 0,0 is the start of first pixel and x-axis last position 200 and y-axis is 300.

Generating images

There are 4 steps involved in generating images

1. Create a blank canvas

2. Draw images or write on this canvas using different functions

3. Save image to disk or load into browser

4. clear the image from memory

Generating a new image

Generating a new image requires generating a canvas. PHP provides two functions for that
1. imagecreate() that creates pallet based images that support only 255 colors.
2.  imagecreatetruecolor() that create true color images and supports around 16.7 million colors. Images are created with highest possible quality.
 These functions take two parameters those are width and height.
$image = imagecreate(200, 150);

The code above creates a blank image whose width would be 200px and height would be 150px. This function will return an image resource identifier or false in case of errors.

Allocate color to images

To allocate color to an image GD library provides a function imagecolorallocate()
Syntax:
int imagecolorallocate ( resource $image , int $red , int $green , int $blue )

The function takes an image resource and RGB color values for red, green and blue it returns a color identifier that represents a color composed of RGB colors. RGB colors range is from 0-255.

$red    = imagecolorallocate($image, 255, 0, 0);

$white  = imagecolorallocate($image, 255, 255, 255);

$black  = imagecolorallocate($image, 0, 0, 0);

Color code can be specified in Hexadecimal as well.

$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);

$black = imagecolorallocate($image, 0x00, 0x00, 0x00);

Basics  of drawing with GD library in PHP

So you know how to create a blank image and add color to it. Different shapes like points, rectangles, lines, ellipses, arcs, and polygons can be drawn.

How to draw a pixel on an image.

To draw pixel we can use function imagesetpixel.
$canvas     = imagecreate(200, 100)

$grey       = imagecolorallocate($canvas, 230, 230, 230);

$black      = imagecolorallocate($canvas, 0, 0, 0);

imagesetpixel($canvas, 120, 60, $black)
 
header("Content-type: image/png");

imagepng($cnavas)

imagedestroy($canvas);

We created a blank canvas using imagecreate function and storing in $canvas whose width is 200 X 100. Two colors grey and black using imagecolorallocate with parameters $canvas and Red, Green, Blue color values. imagesetpixel method accepts 4 parameters,  first argument is  $canvas variable, then x, y co-ordinates and last argument is color.

A pixel is created on canvas  on 120px from x-axis of left side and 60px from y-axis. Next is the header function that sends image contents to the browser as a PNG image. In order to save this image on hard disk, we can pass image path as an optional argument.

imagepng('/images/pixel.png');

The code above will save the image to images folder with the name pixel.png. We can create PNG, JPG, GIF images using GD library functions. Other functions are imagejpeg(), imagegif().  Finally we clear image from memory using imagedestroy() function

How to draw line using GD library in php

To draw lines using GD library  we use a function imageline.
Syntax:
bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
In the function above we have specified 6 parameters. An image resource,  x1, y1  as start points, x2, y2 as end points and finally line’s color.
//Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

//Allocate color
$green = imagecolorallocate($canvas, 132, 135, 28);

//Draw line each with its own color
imageline($canvas, 60, 60, 120, 120, $green);

//Output image and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);

imagedestroy($canvas);

PHP draw line using gd library

How to create a rectangle using GD library in PHP

You can create rectangles using  PHP GD library. imagerectangle function can be used to create rectangles. This function takes 6 parameters.
Syntax:
bool imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

Consider the code below.

// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

// Allocate color
$white = imagecolorallocate($canvas, 255, 255, 255);

// Draw rectangle each with its color
imagerectangle($canvas, 45, 60, 120, 100, $white);

// Output and free from memory

header('Content-Type: image/jpeg');

imagejpeg($canvas);

imagedestroy($canvas);
 Following image is generated by running the code above.
php rectangle using php gd library
Function parameters are  image resource, x1 as top left x coordinate and y1 as  top left y coordinates then
x2 as bottom right x coordinate and y2 as bottom right y coordinate, final argument is the color  identifier.

How to create a circle and ellipses using GD library in PHP

To create circles and ellipses using PHP GD functions we use imageellipse() function
syntax:
bool imageellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )
To create ellipses we have to provide the x, y coordinates for the center of the circle or ellipse then width and height of ellipses and last argument is color.
//Create a blank image.
$image = imagecreatetruecolor(400, 300);

//Choose a color for the ellipse.

$color = imagecolorallocate($image, 255, 255, 255);

//Draw the ellipse.

imageellipse($image, 200, 150, 300, 200, $color);

//Output the image.

header("Content-type: image/png");

imagepng($image);

Circle using php gd library

Create Circle using GD library in php

In order to create a complete Circle we need to specify the same height and width like

 // Draw the circle.
imageellipse($image, 200, 150, 200, 200, $color);

Code to draw a complete circle.

// Create a blank image.

$image = imagecreatetruecolor(400, 300);


// Choose a color for the ellipse.

$color = imagecolorallocate($image, 255, 255, 255);


// Draw the ellipse.

imageellipse($image, 200, 150, 200, 200, $color);


// Output the image.

header("Content-type: image/png");
imagepng($image);

draw circle using gd library

How to draw an arc using GD Library in PHP

imagearc function is used to draw an arc.

Syntax:

bool imagearc (resource $image, int $cx,int $cy, int $width, int $height, int $start,int $end,int $color )
1. $image is image resource, $cx is x-co-ordinate of center

2. $cy is y-co-ordinate of center $width is width of arc

3. $height is height of arc $start arc’s start angle

4. $end is arc’s end angle

5. $color is color identifier created with imagecolorallocate

// create a 1500*150 image
$image     = imagecreatetruecolor(200, 200);

// allocate some colors
$white   = imagecolorallocate($image, 255, 255, 255);

$red     = imagecolorallocate($image, 255,   0,   0);

$green   = imagecolorallocate($image,   0, 255,   0);

$blue    = imagecolorallocate($image,   0,   0, 255);
 
// draw the head
imagearc($image, 100, 100, 200, 200,  0, 360, $white);

// draw mouth
imagearc($image, 100, 100, 150, 150, 25, 155, $red);

// left and then the right eye
imagearc($image,  60,  75,  50,  50,  0, 360, $green);

imagearc($image, 140,  75,  50,  50,  0, 360, $blue);
 
// output image in the browser
header("Content-type: image/png");

imagepng($image);
 
// free memory
imagedestroy($image);

How to create an arc using php GD library

How to create polygons using PHP GD library

Polygon is a shape that has 3 or more vertices. Here you can use function imagepolygon of GD library that draws a polygon. function and takes 4 arguments.
bool imagepolygon ( resource $image , array $points , int $num_points , int $color )
Here $image is an image resource returned by iamgecreate or imagecreatetruecolor. Points is an array that contains polygon vertices, third parameter is number of vertices of polygon, last argument is  a color identifier created with imagecolorallocate().
// Create a blank image
$image = imagecreatetruecolor(400, 300);
 
// Allocate a color for the polygon
$color = imagecolorallocate($image, 255, 255, 255);
 
// Draw the polygon
imagepolygon($image, array(
        0,   0,
        100, 200,
        300, 200
    ),
    3,
    $color);
 
// Output the picture to the browser
header('Content-type: image/png');
 
imagepng($image);

imagedestroy($image);

create polygon using php gd library

In order to do this you have  to create an image resource using imagecreatetruecolor, then allocated black color to $color using imagecolorallocate function. In addition inimagepolygon parameters passed are $image as image resource and an array of vertices.

The first vertex is x, y as 0, 0 second vertex is 100, 200 and third vertex is 300, 200, then we specify the number of vertices. The last argument is $color. This creates a polygon as shown above.

How to create a thumbnail using GD library in PHP

 We can apply different effects to an image or can resize it. There are photo galleries that have image thumbnails when you click on the thumbnail, the large image opens. Large image’s thumbnail can be created very easily using PHP GD library functions.

Generate Thumbnail using GD library in PHP

 $image 		    = imagecreatefromjpeg('flower.jpeg');
 
 $width 		    = imagesx($image);
 
 $height 	 	    = imagesy($image);
 
 $thumb_height              = intval($height / 3);
 
 $thumb_width               = intval($width / 3);
  
 $thumbnail 	            = imagecreatetruecolor($thumb_width, $thumb_height);
  
 imagecopyresampled($thumbnail, $image, 0,0,0,0, $thumb_width, $thumb_height, $width, $height);
  
 header('content-type: image/jpeg');
  
 imagejpeg($thumbnail);
  
 imagedestroy($thumbnail);

 imagedestroy($image);

Original Image:

Flower - generate thumbnail
Generated Thumbnail:
generated thumbnail using php gd library
For this purpose an existing image is opened using imagecreatefromjpeg function. Further this function returns an image object next we determined height and width of image using imagesx and imagesy function. Therefore thumbnail will be one third (1/3) of height and width of the original image so the height and width of the original image are divided by 3.
Here we created an image object for thumbnail using imagecreatetruecolorimagecopyresampled function is used to copy and resize part of an image.
This function takes 10 parameters. This function copies a rectangular area of one image to another image. The first parameter is a thumbnail object while next parameter is original image object. Then x and y coordinate of thumbnail and x and y coordinate of the original image is passed.
 In addition, other parameters are height and width of thumbnail and height and width of the original image.
Finally, the contents of the generated image are passed to the browser. Moreover imagejpeg function creates image and is displayed in browser. Finally, we destroy the original image and thumbnail object.
Similarly there are other functions like imagecopyresized that works likewise as imagecopyresampled but difference is that imagecopyresized is fast but do not do anti aliasing and not good in quality. On the whole imagecopyresampled is slow but it anti alias the image so quality becomes good for image.

Summary

To summarize we have seen the GD library in PHP and image manipulation basics and created some basic shapes and generated a thumbnail.You can read more detail on http://php.net. In next articles soon we will explore watermarking and other advanced functions. Please leave your feedback and valuable comments. Thanks for reading.

Related Articles:

 

Previous Article:

 

Next Article: