Learn the use of GD Library in PHP (3)


In the last article, we have learned an application of GD library, that is, the function of making verification code. However, in real business development, this simple verification code has not been used much. We will make more complex verification codes to use. After all, all kinds of plug-in software can easily crack this simple picture verification code. Of course, we can also simply deform it, such as using Chinese and clicking in order, which can be realized easily. For more complex verification codes, it is recommended to use some open source libraries or APIs.

Today, we will continue to learn some common applications of GD library. We still learn through some small examples, which are also some functions we often use in daily development.

Generate thumbnails

In the daily development process, the size of the pictures uploaded by customers or ourselves in the background may not be the size we need. At this time, the function of thumbnail is more important. Generally, we will generate a thumbnail corresponding to the original drawing on the basis of retaining the original drawing for the display of the unified size page at the front desk.

$w = imagesx($im);
$h = imagesy($im);

$imNew = imagecreatetruecolor($w / 2, $h / 2);

imagecopyresized($imNew, $im, 0, 0, 0, 0, $w / 2, $h / 2, $w, $h);

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

In the above code, the thumbnail we generated is half the size of the original image, and the imagecopied() function is used. Its parameters are the new image canvas, the original image, the X and Y coordinate starting points of the new image, the X and Y coordinate starting points of the original image, the size of the new image, and the size of the original image. There are many parameters, but it is easy to understand, that is, reduce the original image to the specified size and put it on the new canvas.


The imagesx () and imagesy () functions do not literally understand why X and Y coordinate points are used. They actually obtain the width and height of the image handle file. If we output a picture in JPG format, we can also specify its compression ratio.

$w = imagesx($im);
$h = imagesy($im);

$imNew = imagecreatetruecolor($w / 2, $h / 2);

imagecopyresized($imNew, $im, 0, 0, 0, 0, $w / 2, $h / 2, $w, $h);

header("Content-type: image/jpg");
imagejpeg($imNew, null, 10);

That is, the last parameter of imagejpeg() function is the same as the compression ratio when PS exports pictures. If the number is smaller, the compression ratio is higher, the number is larger, and the compression ratio is lower, the picture quality will be better. The default value is 75, and you can set the compression ratio from 0 to 100. The second parameter is still the path to save the image. The code we test here is output directly from the browser, so we give a null here.


From the picture quality, it is indeed much more blurred than the previous directly reduced picture. Of course, the size of the picture is much smaller. For website optimization, the compression ratio of jpg images is generally about 75 of the default value. If it is too small, this too vague situation will appear, which will affect the user experience. According to the specific business analysis, the size of the picture needs to be determined according to our actual situation.

Generates an isometric thumbnail of the specified size

Another business situation is that the picture display size of our front desk is the same, such as the display of commodity pictures in the list. At this time, many pictures may lose their proportion when they are directly compressed. For example, we uploaded a 16:9 wide picture, and the picture position of the foreground list page is 4:3. Here, we have to wait for the proportion to be reduced according to the maximum width or height, and the extra parts are left with white edges or transparent edges. At this time, Just calculate the scale of the picture.

$w = imagesx($im);
$h = imagesy($im);

$imNew = imagecreatetruecolor(202, 152);
imagefill($imNew, 0, 0, imagecolorallocate($imNew, 255, 255, 255));
imagerectangle($imNew, 0, 0, 201, 151, imagecolorallocate($imNew, 0, 0, 0));

$sW = 0;
$sH = 0;
if ($w / $h > 200 / 150) {
    $q = 200 / $w;
    $sH = $h * $q;
    $sW = $w * $q;
    $sX = 0;
    $sY = (150 - $sH) / 2;
} else {
    $q = 150 / $h;
    $sH = $h * $q;
    $sW = $w * $q;
    $sX = (200 - $sW) / 2;
    $sY = 0;

imagecopyresized($imNew, $im, $sX + 2, $sY + 1, 0, 0, $sW, $sH, $w, $h);

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

In the test code, the size we specified is 200 * 150 picture size, that is, 4:3 picture specification. The picture to be operated is a non-standard picture of 300 * 244. At this time, we calculate the width / height ratio to determine whether to reduce based on width or height. If the aspect ratio of the original image is greater than the image aspect ratio specified by us, it is considered to be reduced based on the width. On the contrary, it is reduced by height. Similarly, the specific width and height results are reduced in equal proportion based on the corresponding ratio. At the same time, we have to calculate the position of the picture and put it in the middle. Finally, put the reduced size into the canvas of the specified size.


The canvas in our test code has two more pixels to draw the black border and to demonstrate that it can be seen clearly.

It can be seen that after equal scaling, we scale based on the height of the original image, so white edges will appear on both sides of the image. If it is based on width, white edges will appear above and below the picture. Of course, if the scale of the original image is the same as that we need, the whole canvas will be completely filled. You can test it with pictures of other sizes.

Image watermarking

In addition to thumbnails, the function of adding watermark is also a necessary function in many business development. In fact, there is no need to say more about the direct text watermark. Imagettftext() in the previous article can be added directly. Just specify a transparent color for it with the imagecolorallocatealpha() function. Today we are mainly talking about the addition of image watermark.

$imNew = imagecreatetruecolor(150, 30);

imagecolortransparent($imNew, imagecolorallocatealpha($imNew, 255, 255, 255, 128));
imagesavealpha($imNew, true);

$font = '../font/msyh.ttf';
Imagettftext ($imnew, 16, 0, 11, 21, imagecolorallocate ($imnew, 255, 255), $font, 'hard core project manager');

if (imagesx($im) > 150 + 10 && imagesy($im) > 60 + 10) {
    imagecopy($im, $imNew, imagesx($im) - 150 - 10, imagesy($im) - 30 - 10, 0, 0, 150, 30);

    imagecopymerge($im, $imNew, imagesx($im) - 150 - 10, imagesy($im) - 60 - 10, 0, 0, 150, 30, 50);

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

First, we specify a transparent canvas through imagecolortransparent () and imagesavealpha (). Then a text image is generated by imagettftext(). Note that here is the picture, not the text added directly.

Next, use imagecopy () or imagecopymerge () to copy the watermark image onto the original image. The difference between these two functions is that imagecopymerge() has an additional parameter to specify the transparency of the channel when merging pictures. That is, if it is a picture without transparency, you can directly use this function to increase the transparency effect of the picture.

The judgment before adding watermark is used to judge whether the image size is suitable for adding watermark. If the image is smaller than the watermark file, do not add watermark, or reduce the watermark before adding it.


In this way, the simple watermark addition is completed. In fact, you can find many encapsulated watermark adding classes on the Internet, or there are many ready-made libraries in composer. Here is just a simple effect for you to learn and review.


There are many functions about the picture GD library, but to be honest, the author has not used much now. Why? In actual business development, we are used to cloud storage such as OSS, qiniu and upyun. It is very convenient to zoom the picture, add watermark, or even simply edit some PS. And the most important thing is that we don’t need to occupy our server storage resources and bandwidth resources. Why not. In my current work, the program code server basically only needs the original size of about 20g. It just runs the code and does not store uploaded files, pictures and static resources.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202012/source/3. Learn the use of GD Library in PHP (III). 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

Recommended Today

Beautify your code VB (VBS) code formatting implementation code

However, vb.net does have many new functions that VB6 does not have. The automatic typesetting of code is one, which is the function we want to realize today – VB code formatting.Let’s look at the effect: Before formatting: Copy codeThe code is as follows: For i = 0 To WebBrowser1.Document.All.length – 1 If WebBrowser1.Document.All(i).tagName = […]