In the last article, we have learned an application of the GD library, which is a very commonly used function of making verification codes. However, in real business development, this simple verification code has not been used much, and you will create more complex verification codes to use. After all, all kinds of plug-in software can easily crack this simple image verification code. Of course, we can also simply deform it, such as using Chinese and then clicking in order, these are relatively simple to achieve. For more complex verification codes, it is recommended to use some open source libraries or apis.

Today, we will continue to learn some commonly used applications of the GD library. It is still learning through some small examples, which are also some of the functions that we use very often in daily development.

Generate thumbnail

In the daily development process, whether it is a picture uploaded by a customer or ourselves in the background, the size may not necessarily be the size we need. At this time, the thumbnail function is more important. Generally, we will generate a thumbnail corresponding to the original image on the basis of retaining the original image for the display of the uniform 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");
imagejpeg($imNew);
imagedestroy($imNew);

In the above code, the thumbnail we generated is half the size of the original image, and the function imagecopyresized() is used. Its parameters are the new image canvas, the original image, the x and y coordinate starting point of the new image, and the original image The starting point of x and y coordinates, the size of the new image, and the size of the original image. There are more parameters, but it's easier to understand, just shrink the original image to the specified size and put it on the new canvas.

/img/bVcUjBJ

The imagesx() and imagesy() functions should not be understood literally why the x and y coordinate points and the like, they are actually 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);
imagedestroy($imNew);

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

/img/bVcUjBK

Judging from the picture quality, it is indeed much blurred than the previous directly reduced picture. Of course, the size of the picture is also much smaller. For website optimization, the compression ratio of jpg images is generally around 75 by default. If it is too small, this kind of obscure situation will appear and affect the user's experience. For specific business analysis, the size of the image required depends on our actual situation.

Generate proportional thumbnails of specified size

Another business situation is that the size of the pictures displayed on our front desk is the same, such as the display of product pictures in the list. At this time, many pictures may lose their proportions if they are directly compressed. For example, we uploaded a 16:9 large-width picture, and the picture position on the front-end list page is a 4:3 picture. Here we have to keep the ratio according to the maximum width. Or the maximum height is reduced, and the extra part is left blank or transparent. At this time, just calculate the proportion 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");
imagejpeg($imNew);
imagedestroy($imNew);

In the test code, the size we specified is a picture size of 200*150, which is a 4:3 picture size. The picture that needs to be manipulated is a non-standard picture with a size of 300*244. At this time, we calculate the width/height ratio to determine whether to shrink based on width or height. If the aspect ratio of the original image is greater than the image aspect ratio we specified, it is considered to be reduced based on the width. On the contrary, it is to shrink by height. Similarly, the specific width and height results of the algorithm are all based on the corresponding ratio for proportional reduction. At the same time, we have to calculate the position of the picture, which should be placed in the center. Finally, put the reduced size into the canvas of the specified size.

/img/bVcUjBL

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

As you can see, we scaled the image based on the height of the original image after equal scaling, so white edges will appear on both sides of the image. If it is based on the width, there will be white borders on the top and bottom of the picture. Of course, if the ratio of the original image is the same as the ratio we need, it will completely fill the entire canvas. You can test it yourself with pictures of other sizes.

Picture watermark

In addition to thumbnails, the function of adding watermarks is also a must-have function in many business developments. The direct text watermark is actually needless to say, the imagettftext() in the previous article can be added directly, just use the imagecolorallocatealpha() function to specify a transparent color. Today we are mainly talking about the addition of image watermarks.

$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, 255), $font, '硬核项目经理');

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");
imagejpeg($im);
imagedestroy($im);

First, we specify a transparent canvas through imagecolortransparent() and imagesavealpha(). Then generate a text picture through imagettftext(). Note that this is a picture, not directly added text.

Then, use imagecopy() or imagecopymerge() to copy the watermark image to the original image. The difference between these two functions is that imagecopymerge() has an extra parameter to specify the transparency of the channel when the image is merged. That is to say, if it is a picture without transparency, you can directly use this function to make the picture more transparent. .

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

/img/bVcUjBM

In this way, simply adding the watermark is complete. In fact, you can find a lot of predecessors' already packaged watermarking classes on the Internet, or there are many ready-made libraries in Composer, here is just a handwritten simple effect for everyone to study and review.

Summarize

There are many more functions of the image GD library, but to be honest, I don't use much now. why? In actual business development, everyone is actually accustomed to using cloud storage such as oss, Qiniu, and upyun. Whether it is image scaling, watermarking, or even simple PS editing, it is very convenient. And the most important thing is that we no longer need to occupy our server storage resources and bandwidth resources, why not do it. Like 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 together (3).php

Reference documents:

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

Searchable on their respective media platforms [Hardcore Project Manager]


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