Introduction of PHP Image Compression Function

  • 2021-12-04 09:34:20
  • OfStack

Thumbnail generation is often involved in php program development. It is not difficult to generate thumbnails by php, but do you know that php can optimize the quality of thumbnails generated? That is to say, php can control the clarity of the generated thumbnail and the volume of the generated thumbnail. Let's take a look at how to use php to optimize our compressed pictures.

For how to use php to generate thumbnails here is not introduced, we can refer to this site below this article: PHP automatic generation thumbnail function source code example

First of all, let's take a look at the program code for compressing pictures with php:


<?php
header('Content-type: image/png');
$image=@imagecreatefrompng('//www.ofstack.com/test.png');
imagepng($image,'test.png',0); // Pay attention to the number at the back 0 In this case, the compression level, the parameter range: 0-9*/
imagedestroy($image);
?>

The third parameter of the above imagepng function is what this article will analyze, which means the quality level of the generated picture. It can be divided into 10 grades (0-9). At grade 0, there is no compression, and the picture will not be distorted. The picture is the clearest, but the volume of the picture is also the largest. With the increasing number of compression grades, the picture will become less and less clear, but the volume of the compressed picture can be reduced to 50% of the original, and the compression ratio is still quite large.

Let's look at a specific example. Now the volume of an original image is 125k. The following are the test results after different compression levels:

imagepng($img,null,0); -- > Size = 225K
imagepng($img,null,1); -- > Size = 85.9K
imagepng($img,null,2); -- > Size = 83.7K
imagepng($img,null,3); -- > Size = 80.9K
imagepng($img,null,4); -- > Size = 74.6K
imagepng($img,null,5); -- > Size = 73.8K
imagepng($img,null,6); -- > Size = 73K
imagepng($img,null,7); -- > Size = 72.4K
imagepng($img,null,8); -- > Size = 71K
imagepng($img,null,9); -- > Size = 70.6K

Note that when the compression level is 0, the volume is larger than the original image because the original image is actually slightly compressed, and the compression level of 0 means that there is no compression at all, so its volume will be larger than the original image.

According to the above conclusions and the actual test results, the conclusion is that when optimizing the picture, it is more appropriate to adopt 2 grades, and the picture has no distortion, but the volume is reduced by 30%, thus achieving the purpose of optimization. If you use 6, 7, 8, 9 levels of compression, the image distortion, but the volume reduction is not obvious. Therefore, it is not appropriate to use these levels to compress and optimize pictures.

Summarize


Related articles: