In the daily development process, the most commonly used function of the GD library is to help us process some pictures. Of course, in addition to processing 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 at the end we will also make a very simple example of image verification code.

Create pictures and assign colors

First of all, we have to create a picture canvas. Just like PhotoShop, any drawing must be done under a canvas.

// 创建一个 200X200 的图像
$img = imagecreatetruecolor(200, 200);
// 分配颜色
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
$red = imagecolorallocate($img, 255, 0, 0);

// 带透明通道的颜色
$alphaRed = imagecolorclosestalpha($img, 255, 0, 0, 50);

The imagecreatetruecolor() function is used to create a true color image. The difference between it and imagecreate() is that imagecreate() creates a palette-based image. The process of filling the canvas with color is different. imagecreate() does not need to use imagefill() to fill the background color, and directly using imagecolorallocate() will fill it with the color of the first call to imagecolorallocate(). The picture file handles they return are all handle objects needed for later operations.

imagecolorallocate() is to assign colors to the image. Here we define several colors. In addition, we use imagecolorclosestalpha() to define a color with a channel that is also transparent. Its last parameter is the 0-100 transparency setting.

Fill background color

Next, since we are using imagecreatetruecolor(), we need to fill the canvas with the background color.

// 填充背景色
imagefill($img, 0, 0, $black);

Arc, straight line, rectangle

Whether it is drawing a line or drawing an arc, it is just a few simple function calls.

// 画一个白色的圆
imagearc($img, 100, 100, 150, 150, 0, 360, $white);

// 画一条线段
imageline($img, 20, 180, 120, 120, $white);

// 填充一个带透明的矩形
imagefilledrectangle($img, 30, 30, 70, 70, $alphaRed);

The imagearc() function itself is used to draw arcs, 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, and the sixth and seventh parameters specify the arc The starting position (specified in angle), the last parameter is the specified color. With a given 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() for straight line segments are relatively simple. The second and third parameters are the coordinates of the starting point, and the fourth and fifth parameters are the coordinates of the ending point. The two coordinate points are connected to draw a line segment.

imagefilledrectangle() draws a rectangle in a filled way, that is to say, 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 what we fill is the color with transparent effect defined above.

Of course, there are many more graphics and lines that we can draw directly. It should be noted that the filled graphics are basically filled with the keyword fill, and the shape line segments are not filled with fill. For example, if we want a rectangular box, we can use imagerectangle() to draw it. In the same way, if we want to draw a fan-shaped block, we can also use imagefillarc() directly. You can refer to the document for more graphics and line segments. There are more content, so I won't list them here. Today our main function is to generate a verification code, as long as there is a line segment as an interference factor.

Writing

It is also very simple to write directly in the picture.

$string = "I Like PHP!";

// 水平写一个字符
imagechar($img, 5, 70, 50, $string, $red);
// 垂直写一个字符
imagecharup($img, 3, 120, 50, $string, $red);

// 水平写字符串
imagestring($img, 5, 70, 150, $string, $red);
// 垂直写字符串
imagestringup($img, 3, 120, 150, $string, $red);

imagechar() is to write only one character, imagecharup() is to write vertically. imagestring() writes a string, and imagestringup() writes a string vertically. Their second parameter is the size of the font, and the third and fourth parameters are the starting position of the coordinate to start writing. However, if you use these functions to write the content of the picture, one of the main problems is that you cannot specify the font, so that Chinese cannot be output by default. Therefore, we generally use another function to add text to the picture.

// 用 TrueType 字体向图像写入文本
$font = '../font/arial.ttf';
imagettftext($img, 20, 0, 11, 21, $white, $font, $string);

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

Generate picture

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

// 将图像输出到浏览器
header("Content-type: image/png");
imagepng($img);
// 释放内存
imagedestroy($img);

Our test code is to directly output the image to the browser, so we need to specify a file output header. 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 as a file to the path specified by the parameter. If this parameter is not given, it will be directly output to the output buffer just like phpinfo(), that is, the content will be printed directly. Finally, we use imagedestroy() to release the image handle to remove the memory usage of the image file.

In addition to imagepng(), there are also a series of image generation functions such as imagejpeg(), imagegif(), etc. You can check the documentation for yourself.

Having said that, what are the things we drew above?

/img/bVcUh7A

Small example: simple verification code picture

The last small example is what we said at the beginning, a very simple image verification code generation. The current verification code function is actually very complicated. There are various forms of verification codes, mainly for the safety of the system. There are also many ready-made verification code components in Composer for us to use. In fact, we don’t need to implement such verification code functions by ourselves, but for learning, we must always contact and understand, and if it’s something very small For small projects, you can write one by yourself 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++) {
    imageline(
        $img,
        random_int(0, 120),
        random_int(0, 50),
        random_int(0, 120),
        random_int(0, 50),
        $colors[array_rand($colors)]
    );
}
$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;
    }
    imagettftext(
        $img, 
        $fontSize, 
        $c, 
        $x, 
        40, 
        $colors[array_rand($colors)], 
        $font, 
        $char
    );
}
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

The code will not be explained much. Some characters are randomly selected and some line segments are randomly generated. The other is the use of the functions introduced in the article above. The final generated image looks like this:

/img/bVcUh7B

Summarize

Regardless of whether you have written this kind of verification code before, today’s content is believed to be a systematic study and review, because we follow the order from creating a picture canvas, to drawing lines and graphics, and then adding The text, and finally the series of steps to generate a picture. In the future, whether it is an interview or making gadgets by yourself, remember this line and refer to the documentation. After all, the parameters of these functions are still quite long and messy, unless you use them every day, you can't remember them.

Test code:

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

Reference documents:

https://www.php.net/manual/zh/book.image.php

Searchable on their respective media platforms [Hardcore Project Manager]


硬核项目经理
90 声望18 粉丝