Cheap VPS host selection
Provide server host evaluation information

How to compress a PHP image to a specified size

How can I compress a PHP image to a specified size? We can use PHP's GD image processing library to compress the image size. The following is an example code to compress the image to the specified size:

 <? php
 //Specify the original picture path and output picture path
 $src = 'original_image.jpg' ; $out = 'compressed_image.jpg' ; //Specify the width and height of the target picture
 $targetWidth = eight hundred ; $targetHeight = six hundred ; //Create an image object
 $img = imagecreatefromjpeg ( $src ); //Get the width and height of the original picture
 $srcWidth = imagesx ( $img ); $srcHeight = imagesy ( $img ); //Calculate Scaling
 $scale = min ( $targetWidth / $srcWidth , $targetHeight / $srcHeight ); //Calculate the width and height of the target image
 $newWidth = round ( $srcWidth * $scale ); $newHeight = round ( $srcHeight * $scale ); //Create a new blank picture object
 $newImg = imagecreatetruecolor ( $newWidth , $newHeight ); //Copy and resize image
 imagecopyresampled ( $newImg , $img , zero , zero , zero , zero , $newWidth , $newHeight , $srcWidth , $srcHeight ); //Export to file
 imagejpeg ( $newImg , $out ); //Free memory
 imagedestroy ( $img ); imagedestroy ( $newImg ); ?>

In the above code, we first specify the original image path and the output image path, and then specify the width and height of the target image. Next, we created an image object and obtained the width and height of the original image. Then, we calculated the scaling ratio, and calculated the width and height of the target image according to the scaling ratio. Next, we create a new blank image object, copy and resize the original image, and finally output it to a file and free memory.

Please note that this is just a sample code, and the specific compression method and parameters should be adjusted according to actual needs.

Do not reprint without permission: Cheap VPS evaluation » How to compress a PHP image to a specified size