Learn the use of GD Library in PHP (2)


In the daily development process, the most commonly used function of GD library is to help us deal with pictures. Of course, in addition to dealing with existing pictures, it can also draw pictures directly, just like our most common picture verification code. Today’s content is mainly related to drawing, so finally we will also do a very simple example of image verification code.

Create a picture and specify a color

First, we need to create a picture Canvas. Just like Photoshop, any drawing should be carried out under a canvas.

//Create a 200x200 image
$img = imagecreatetruecolor(200, 200);
//Assign color
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
$red = imagecolorallocate($img, 255, 0, 0);

//Color with transparent channel
$alphaRed = imagecolorclosestalpha($img, 255, 0, 0, 50);

The imagecreatetruecolor() function is used to create a true color image. The difference between imagecreate() and imagecreate() is that imagecreate() creates a palette based image. They fill the canvas with different colors. Imagecreate () does not need to use imagefill () to fill the background color. Directly using imagecolorallocate () will fill the canvas with the color of imagecolorallocate () called for the first time. The picture file handles they return are handle objects required for later operations.

Imagecolorallocate() is to assign colors to the picture. Here we define several colors. In addition, imagecolorclosetalpha() is used to define a color with channel, that is, transparent effect. Its last parameter is the transparency setting of 0-100.

Fill background color

Next, because we use imagecreatetruecolor (), we need to fill the canvas with the background color.

//Fill background color
imagefill($img, 0, 0, $black);

Arc, straight line, rectangle

Whether drawing a line or an arc is just some simple function calls.

//Draw a white circle
imagearc($img, 100, 100, 150, 150, 0, 360, $white);

//Draw a line segment
imageline($img, 20, 180, 120, 120, $white);

//Fills a rectangle with transparency
imagefilledrectangle($img, 30, 30, 70, 70, $alphaRed);

The imagearc() function itself is used to draw an arc. The second and third parameters are used to specify the position of the center of the circle, the fourth and fifth parameters specify the width and height of the circle, the sixth and seventh parameters specify the starting position of the arc (specified by angle), and the last parameter is the specified color. Given an angle from 0 to 360 degrees, we draw a circle. If it is not the specified full 360 degrees, it will be an arc.

The parameters of the function imageline () of the line segment are relatively simple. The second and third parameters are the coordinates of the starting point, the fourth and fifth parameters are the coordinates of the ending point. A line segment is drawn by connecting the two coordinate points.

Imagefilledrectangle () draws a rectangle by filling, that is, the rectangle we draw is filled with color inside, not the stroke of the line. Its parameter coordinates are the same as the line segment, and we fill in the color with transparent effect defined above.

Of course, there are still many figures and lines that we can draw directly. It should be noted that those with the fill keyword are basically filled graphics, while those without the fill keyword are shape segments. For example, if we want a rectangular box, we can use imagerectangle () to draw it. Similarly, if we want to draw a sector, we can also directly use imagefillarc(). For more graphics and line segments, you can refer to the document. There are many contents, which are not listed here. Today, our main function is to generate a verification code, as long as there is a line segment as an interference factor.


It’s also easy to write directly in the picture.

$string = "I Like PHP!";

//Write one character horizontally
imagechar($img, 5, 70, 50, $string, $red);
//Write one character vertically
imagecharup($img, 3, 120, 50, $string, $red);

//Write string horizontally
imagestring($img, 5, 70, 150, $string, $red);
//Write string vertically
imagestringup($img, 3, 120, 150, $string, $red);

Imagechar () writes only one character, and imagecharup () writes vertically. Imagestring () writes strings, and imagestringup () writes strings vertically. The second parameter is the font size, and the third and fourth parameters are the starting position of the coordinates to start writing. However, if you use these functions to write the content of the picture, the main problem is that you can’t specify the font, so Chinese can’t be output by default. Therefore, we usually use another function to add text to the picture.

//Writing text to an image using TrueType fonts
$font = '../font/arial.ttf';
imagettftext($img, 20, 0, 11, 21, $white, $font, $string);

Imagettftext() function can add text content to the picture through the specified font. With the support of font file, the written text looks much better. More importantly, it can easily adjust the text size and tilt angle. The second parameter is to specify the size of the text. The third parameter is to specify the tilt angle of the text, that is, we can rotate the text.

Generate picture

Finally, of course, is to generate and output pictures!

//Export image to browser
header("Content-type: image/png");
//Free memory

Our test code is to output pictures directly to the browser, so we need to specify a header for file output. Use imagepng() to generate a picture in PNG format. It also has a second parameter. If the second parameter is given, the picture will be directly saved in the path specified by the parameter in the form of a file. If this parameter is not given, it will be output directly to the output buffer like phpinfo (), that is, the content will be printed directly. Finally, we use imagedestroy () to release the image handle and relieve the memory occupation of the image file.

In addition to imagepng (), there are a series of image generation functions such as imagejpeg (), imagegif (), etc. you can refer to the documentation to learn about them.

Having said so much, what do we draw from the pile of things above?


Small example: simple verification code picture

The last small example is what we said at the beginning, a very simple image verification code generation. Now the function of verification code is actually very complex. There are various forms of verification code, mainly for the sake of system security. Similarly, there are many ready-made verification code components in composer for us to use. In fact, we don’t need to realize such verification code function by ourselves, but we always need to contact and understand it when learning. Moreover, if it is a small project, we can write one by ourselves to practice.

$img = imagecreatetruecolor(120, 50);
imagefill($img, 0, 0, imagecolorallocate($img, 255, 255, 255));

$colors = [
    imagecolorallocate($img, 0, 0, 0),
    imagecolorallocate($img, 255, 0, 0),
    imagecolorallocate($img, 0, 255, 0),
    imagecolorallocate($img, 0, 0, 255),

$chars = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));

for ($i = 0; $i < 10; $i++) {
        random_int(0, 120),
        random_int(0, 50),
        random_int(0, 120),
        random_int(0, 50),
$font = '../font/arial.ttf';
for ($i = 0; $i < 4; $i++) {
    $char = $chars[array_rand($chars)];
    $fontSize = random_int(18, 24);
    $c = random_int(-20, 20);
    $x = $i * 26;
    if ($x == 0) {
        $x = 5;
header("Content-type: image/png");

The code will not explain more. Take some characters randomly and generate some line segments randomly. Others are the use of the functions introduced in the above article. The final generated image looks like this:



Whether or not we have written this verification code gadget before, today’s content is believed to be a systematic learning and review, because we follow the sequence from creating a picture Canvas, drawing lines and graphics, adding text, and finally generating pictures. In the future, whether it’s an interview or making your own gadgets, remember this line, and then refer to the documentation. After all, the parameters of these functions are still very long and messy. Unless you use them every day, you can’t really remember them.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202012/source/2. Learn the use of GD Library in PHP (II). PHP

Reference documents:


Official account: hard core project manager

Add wechat / QQ friends: [xiaoyuezigonggong / 149844827] get free PHP and project management learning materials

Tiktok, official account, voice, headline search, hard core project manager.

Station B ID: 482780532