This is the 21st day of my participation in the August Text Challenge.More challenges in August

In the last article we looked at an application of the GD library, which is the very common ability to make captchas. However, in real business development, this simple captcha is not used much, people will make more complex captcha to use. After all, plugins can easily crack this simple image captcha. Of course, we can also simply transform it, such as using Chinese and click in order and so on, these are relatively easy to achieve. More complex captcha implementations are recommended using open source libraries or apis.

Today, we will continue to look at some common uses of the GD library. Again, I’m going to go through some small examples, but also some features that we use very often in our 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, so the function of thumbnail is more important. Generally, we will generate a thumbnail corresponding to the original image on the basis of preserving the original image for the display of the unified size page in the foreground.

$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);
Copy the code

In this code, we generated a thumbnail that was half the size of the original image using the function ImagecopyResized (), which took the new image canvas, the original image, the x and Y starting points of the new image, the x and Y starting points of the original image, the size of the new image, and the size of the original image. More parameters, but also easier to understand, is to reduce the original image to the specified size and put on a new canvas.

The imagesx() and imagesy() functions are not meant to be taken literally as x and y points, they are meant to get the width and height of the image handle file. If we output a JPG image, 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);
Copy the code

The last parameter of imagejpeg() is the same as the compression ratio of the image exported by PHOTOSHOP. The smaller the number, the higher the compression ratio, and the larger the number, the lower the compression ratio, the better the image quality. The default value is 75, and the compression ratio can be set from 0 to 100. The second argument is still the path to save the image. The code we are testing here is output directly from the browser, so we are giving it null.

From the picture quality, it is indeed a direct reduction of the picture blurred a lot. Of course, the size of the image is also much smaller. For site optimization, JPG compression ratio is usually around the default value of 75. If it’s too small, it can get too fuzzy and affect the user experience. Specific business specific analysis, the size of the picture needs to be determined according to our actual situation.

Generates an equal-scale thumbnail of the specified size

Another business situation is that the picture display size of our front desk is the same, for example, the product picture is displayed in the list. At this time, many pictures may lose the proportion directly compressed, for example, we uploaded a 16:9 large and wide picture, and the picture position of the foreground list page is 4:3 picture, here we have to wait for the proportion to be reduced according to the maximum width or height, while the extra part of the white edge or transparent edge, 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");
imagejpeg($imNew);
imagedestroy($imNew);
Copy the code

In our test code, we specified a 200 × 150 image size, which is 4:3 image size. The image that needs to be manipulated is a less standard image of 300 by 244. At this point, we calculate the width/height ratio to determine whether to zoom out based on width or height. If the aspect ratio of the original picture is greater than the aspect ratio of the picture specified by us, the reduction is considered based on the width. Conversely, it is reduced by height. Similarly, the algorithm of specific width and height results is equal scale reduction based on the corresponding ratio. At the same time, we need to calculate the position of the image, and put it in the middle. Finally, the reduced size is placed on the canvas of the specified size.

We added two extra pixels to the canvas in this test code to draw the black border and to demonstrate clarity.

As you can see, when we scale, we scale against the height of the original image, so there are white edges on both sides of the image. If you base the image on width, you will see white edges above and below the image. Of course, if the original image is the same scale as we need it to be, it will completely fill the canvas. You can test it out for yourself with images of other sizes.

Image watermarking

In addition to thumbnails, the watermarking function is also a necessary function in many business development. In the previous article, you can add a transparent color to imagettfText () using the imagecoloralLocateAlpha () function. Today we are mainly talking about the addition of picture watermarking.

$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.'Hardcore 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");
imagejpeg($im);
imagedestroy($im);
Copy the code

First, we specify a transparent canvas with imagecolorTransparent () and Imagesavealpha (). It then generates a text image from imagettfText (). Note that this is a picture, not text.

Next, use Imagecopy () or ImagecopyMerge () to copy the watermark image to the original image. The difference between imagecopyMerge () and imagecopyMerge is that imagecopyMerge () takes an additional parameter to specify the transparency of the channel. This means that if an image is not transparent, you can use this function to make the image transparent.

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

In this way, simple watermarking is done. In fact, you can find many classes for adding watermarks that have been encapsulated by predecessors on the Internet, or there are many ready-made libraries in Composer. Here, I just write a simple effect for you to learn and review.

conclusion

There are many other functions of the Picture GD library, but to be honest, I have not used much now. Why is that? In actual business development, everyone has been used to using oss, Seven Cows, Upyun and other cloud storage. Whether it’s zooming in and out of images, adding watermarks, or even simply doing some PHOTOSHOP editing, it’s really handy. And the most important is no longer need to occupy our server storage resources and bandwidth resources, why not? In my current job, the application code server is basically a raw 20GB or so, running the code and not storing uploaded files, images, or static resources.

Test code:

Github.com/zhangyue050…

Reference Documents:

www.php.net/manual/zh/b…