PHP: Create images

In this tutorial we will show how to create images with PHP.

Requeriments: GD library must be installed in the server (probably it is installed).
Procedure:    We will show small pieces of code, and the resulting figures.
    The code will be explained line by line. New lines will be added to the code so that the complexity of the image increases.

Create new images
  Code 1: create a 200x200 square
  Code 2: draw lines
  Code 3: draw rectangles
  Code 4: draw ellipses
  Code 5: draw arcs
  Code 6: add text to the image
Manipulate images
  Code 7: rotate images
  Code 8: resize images
  Code 9: get a portion of the image
  Code 10: modify an existing image
Images on the fly
  Code 11: create and show images on the fly



Code 1: create a 200x200 square (and a bit more)
1
2
3
4
5
6
7
8
9
10
11
<?php
create_image();
print "<img src=image.png?".date("U").">";

function  create_image(){
        $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 0);  // yellow
        imagepng($im,"image.png");
        imagedestroy($im);
}
?>
image 1

Lanes 1 and 11: opening and closing tags for php
Lane 2: request to execute function  create_image(), which is located in lines 5 to 10. The function will create the image.
Lane 3: print out the html code necessary to display the newly created image.
Lanes 5 to 10: contains the function which will create the new images.
 imagecolorallocate($im, 255, 255, 0):


Code 2: draw lines
lines 9 to 11 added to code 1 above
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
create_image();
print "<img src=image.png?".date("U").">";

function  create_image(){
        $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 0);   // yellow
       
        $red = imagecolorallocate($im, 255, 0, 0);                  // red
        $blue = imagecolorallocate($im, 0, 0, 255);                 // blue
        imageline ($im,   5,  5, 195, 5, $red);
        imageline ($im,   5,  5, 195, 195, $blue);
       
        imagepng($im,"image.png");
        imagedestroy($im);
}
?>
 image 2

Lanes 9 and 10: new colors are added to the image (as explained earlier for line 7).
Lane 11: horizontal line is draw.
Lane 12: diagonal line is draw.

To draw lines imageline() command is used. Check the picture bellow to understand the parameters used with this command.
             
imageline ($im,  X1, Y1, X2, Y2, $color);

where X1, Y1, X2 and Y2 are the positions  within the image.

For example, the red line starts at
  X1=5 and Y1=5
and ends at
  X2=195 and Y2=5


position within image


Code 3: draw rectangles
similar to code 2, but lines 11 and 12 has been changed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
create_image();
print "<img src=image.png?".date("U").">";

function  create_image(){
        $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 0);   // yellow
       
        $red = imagecolorallocate($im, 255, 0, 0);                  // red
        $blue = imagecolorallocate($im, 0, 0, 255);                 // blue
        imagerectangle ($im,   5,  10, 195, 50, $red);
        imagefilledrectangle ($im,   5,  100, 195, 140, $blue);
       
        imagepng($im,"image.png");
        imagedestroy($im);
}
?>
 image 3

Lane 11: a red rectangle is drawn (only the outer line)..
Lane 12: a blue rectangle is drawn (a filled one).

To draw the rectangles, position of upper left corner and bottom right corner are considered. Check the picture bellow to understand the parameters used with those commands.

             
imagerectangle ($im,  X1, Y1, X2, Y2, $color);
imagefilledectangle ($im,  X1, Y1, X2, Y2, $color);


For example, the red rectangle starts at
  X1=5 and Y1=10
and ends at
  X2=195 and Y2=50


image 3b


Code 4: draw ellipses
similar to code 2, but lines 11 and 12 has been changed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
create_image();
print "<img src=image.png?".date("U").">";

function  create_image(){
        $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 0);   // yellow
       
        $red = imagecolorallocate($im, 255, 0, 0);                  // red
        $blue = imagecolorallocate($im, 0, 0, 255);                 // blue
        imageellipse($im, 50, 50, 40, 60, $red);
        imagefilledellipse($im, 150, 150, 60, 40, $blue);
       
        imagepng($im,"image.png");
        imagedestroy($im);
}
?>
 image 4

Lane 11: a red ellipse is drawn (only the outer line)..
Lane 12: a blue ellipse is drawn (a filled one).

To draw the ellipses, position of the center of the ellipse, and its width and height  are considered. Check the picture bellow to understand the parameters used with those commands.

             
imageellipse($im, X, Y, width, height, $color);
imagefilledellipse($im, X, Y, width, height,$color);

For example, the center of the red ellipse is
located at
  X=50
  Y=50
and the dimensions are
  width = 40
  height= 60


image 4
To draw a circle you may draw an ellipse with width=height.


Code 5: draw arcs
similar to code 2, but lines 12 to 20 has been added
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
create_image();
print "<img src=image.png?".date("U").">";

function  create_image(){
        $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 0);   // yellow
       
        $red = imagecolorallocate($im, 255, 0, 0);                  // red
        $blue = imagecolorallocate($im, 0, 0, 255);                 // blue
       
        imagearc($im, 20, 50, 40, 60, 0, 90, $red);
        imagearc($im, 70, 50, 40, 60, 0, 180, $red);
        imagearc($im, 120, 50, 40, 60, 0, 270, $red);
        imagearc($im, 170, 50, 40, 60, 0, 360, $red);

        imagefilledarc($im, 20, 150, 40, 60, 0, 90, $blue, IMG_ARC_PIE);
        imagefilledarc($im, 70, 150, 40, 60, 0, 180, $blue, IMG_ARC_PIE);
        imagefilledarc($im, 120, 150, 40, 60, 0, 270, $blue, IMG_ARC_PIE);
        imagefilledarc($im, 170, 150, 40, 60, 0, 360, $blue, IMG_ARC_PIE);
       
        imagepng($im,"image.png");
        imagedestroy($im);
}
?>
 image 5

Lanes 12-15: a red arc is drawn (only the outer line)..
Lanes 17-20: a blue arc is drawn (a filled one).

The basic codes used is
    imagearc ( $im, X, Y, width, height, arc start, arc end, $color)
    imagefilledarc ( $im, X, Y, width, height, arc start, arc end, $color, flag )

X and Y define thy position of the center of the arc within the image
Width and height are the dimensions of the complete circle formed by the arc.
arc start and arc end are the start and the end of the arc in degrees. If start is zero, as in the example, the figure will start in the right.
Flags are specific options available for those commands. Visit the commands information to get additional information about all possible flags.
Check the figure bellow for better understanding  of  the commands above.

image 5b

The commands  imagearc () and imagefilledarc () may also be used to draw circles (width=height, arc start=0 and arc end=360).

Other figures you may draw:
    imagepolygon () -- Draw a polygon
    imagefilledpolygon () -- Draw a filled polygon
      

Code 6: add text to the image
lines 8 to 16 has been added to code 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
create_image();
print "<img src=image.png?".date("U").">";

function  create_image(){
        $im = @imagecreate(200, 200)or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 0);  // yellow
        $red = imagecolorallocate($im, 255, 0, 0);      // red

        imagestring($im, 1,file:///C:/apache2triad/htdocs/0image/tutorial1.html 5,  10, "Hello !", $red);
        imagestring($im, 2, 5,  50, "Hello !", $red);
        imagestring($im, 3, 5,  90, "Hello !", $red);
        imagestring($im, 4, 5, 130, "Hello !", $red);
        imagestring($im, 5, 5, 170, "Hello !", $red);

        imagestringup($im, 5, 140, 150, "Hello !", $red);

        imagepng($im,"image.png");
        imagedestroy($im);
}
?>
image 1

Lane 8: defines red color
Lanes 10 to 14: adds text to image. In this simple example, built-in fonts will be used.
    imagestring ($im, size, X,  Y, text, $red);
    The size will be 1 to 5.
    X and Y are the positions where the text will start.

Lane 16: similar to previous lines, but text is written in vertical.


Code 7: rotate image
This is new code
1
2
3
4
5
6
7
8
9
10
11
<?php

$im = imagecreatefrompng("image.png");
$yellow = imagecolorallocate($im, 255, 255, 0);
$rotate = imagerotate($im, 90,$yellow);
imagepng($rotate,"image_rotated.png");
imagedestroy($im);

print "<img src=image.png> - <img src=image_rotated.png>";

?>
image 1 - image 6 rotated

Lane 3: the information about the image is stored in variable $im.
      In this case, the information has been obtained from an existing png image with the command imagecreatefrompng ()
      If the reference image has a different extension, other commands may be used:
imagecreatefromgif -- Create a new image from file or URL
imagecreatefromjpeg -- Create a new image from file or URL
imagecreatefrompng -- Create a new image from file or URL
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL




          More options here.
Lanes 4: a new color is used to  be use in next line
Lanes 5: the information about the image in $im is modified with imagerotate () and stored in a new variable: $rotate
    imagerotate ($im, degrees, $color);
    degrees are used to define the rotation angle. Values may be  positive  (90, 180...) or negative (-90,-180...).
    $color indicates the color to be used as background when necessary (when rotation angle is different to 90, 180 and 270).
    For example when rotation is 45 degrees, the size of the figure will be altered, as shown bellow. As a consequence a background color is required to fill the new surface.
    In this example, we have define the background color as red.
image 8c

Lane 6 and 7: the image is saved to a file and frees memory (as  described in  code 1).
Lane 9: Both images are shown (original and new).


Code 8: resize image
This is new code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

$original_image = imagecreatefrompng("image.png");

// obtain data from selected image
$image_info = getimagesize("image.png");
// data contained in array $image_info may be displayed in next line
// print_r($image_info)

$width  = $image_info[0];    // width of the image
$height = $image_info[1];    // height of the image

// we will reduce image size to 70%, so new dimensions must be calculate
$new_width  = round ($width*0.7);
$new_height = round ($height*0.7);

$new_image = imagecreate($new_width, $new_height);
imagecopyresized($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

imagepng($new_image,"resized_image.png");
imagedestroy($new_image);

print "<img src=image.png> <br>Resized image<BR> <img src=resized_image.png>";

?>
image 1
Resized image
image 9

Lane 3: the information about the original image is stored in variable $original_image.
Lines 6: size of original image is obtained. The info is contained in an array as explained in the code.
Lanes 10 and 11: width and height of the image are extracted from the array and stored in variables $width and $height.
Lanes 13 to 15: In this example, the image will be reduce to 70%, so new width and height are computed as shown. To avoid decimals round command is used.
Lane 17: In this line starts the creation process of the new image. Command imagecreate() will  define the dimension of the new image, and variable $new_image will store all information related to the image.
Lane 18: This is the core command of this script. Lets try to explain the command by using a picture which contains all the elements in the command.

image 8 command

    Where:  
                    Xo1, Yo1, Xo2 and Yo2 are the dimensions of the original image
                    Xn1, Yn1, Xn2 and Yn2 are the dimensions of the new image
  

Lane 20 and 21: the image is saved to a file and frees memory (as  described in  code 1).
Lane 23: Both images are shown (original and new).

Code 9: get a portion of the image
Quite similar to code 8, but with a different result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<?php

// get the original image
$original_image = imagecreatefrompng("image.png");

// create new image
$new_image = imagecreate(200, 200);

// define red color (it will be the background of the new image)                 
$red = imagecolorallocate($new_image, 255, 0, 0);
    
imagecopyresized($new_image, $original_image, 75, 75, 0, 0, 100, 100, 100, 100);

imagepng($new_image,"new_image.png");
imagedestroy($new_image);

print "<img src=image.png> <br>New image<BR> <img src=new_image.png>";

?>
image 1
New image
image 9


Lane 4: the information about the original image is stored in variable $original_image.
Lane 7: a new 200x200 pixels image is created.
Lane 10: a color is defined  for the new image.It will be also the background color (for better understanding, check code 7)
Lanes 12: The core command of this script.
       A square area from original image is selected. In this example, the selected area is defined by position (0,0) and position (100,100).
       The selected area is copied to position (75,75) of the new image and dimension of the area are maintained (100x100).
Lane 14 and 15: the new image is saved to a file and frees memory (as  described in  code 1).
Lane 17: Both images are shown (original and new).      

Code 10: modify an image
A rectangle and a text will be added to an already existing image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

<?php

// get the original image
$im = imagecreatefrompng("image.png");

// new color
$blue = imagecolorallocate($im, 0, 0, 255);                 // blue
$red = imagecolorallocate($im, 255, 0, 0);                  // red

imagefilledrectangle ($im,   80,  5, 195, 60, $blue);
imagestring($im, 5, 80, 5, "Modified!", $red);

imagepng($im,"modified_image.png");
imagedestroy($im);

print "<img src=image.png> <br>Modified image<BR> <img src=modified_image.png>";

?>
image 1
Modified image
image 10


Lane 4: a new image is created using an already existing image as a reference.
Lanes 7 and 8: new colors are defined
Lane 10: a rectangle is added to the image (check code 3)
Lane 11: a text is added to the image (check code 6)
Lane 13 and 14: the new image is saved to a file and frees memory (as  described in  code 1).
Lane 16: Both images are shown (original and new).     

Code 11: create and show images in the fly
The image is not save to the disk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php

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

$im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");

$background_color = imagecolorallocate($im, 255, 255, 0);    // yellow
$blue = imagecolorallocate($im, 0, 0, 255);                  // blue

imagestring($im, 3, 5, 5,  "My Text String", $blue);

imagepng($im);
imagedestroy($im);

?>
image 11


Lane 3: In this example, the first information send by the server to the browser is shown in line 3.
    This line indicates that information being send is a png image.

Lanes 5 to 13:
the image is create and send
    Lane 5: a 200x200  image is created
    Lanes 7 and 8: colors used in the image are defined
    Lane 9: a text is added to the image(as  described in  code 6).
    Lane 12: the image is output. As no file is indicate, the image is output ("on the fly").
  


If you like our script, please rate it!
PHPTutorial.info.