How To Compress Image Size Before Uploading In PHP.

Compress Image Size In PHP.

 The large size image may take more time to upload on a server. It also takes more time to load on a page. So it is good practice to minimize the image size before upload on the server. Usually, the user does not optimize the image when uploading through the website. In this case, our application should be able  to optimize the image before upload on the server.

 In this tutorial, We will learn image compression techniques  by using the PHP function. This script is used to optimize the images while uploading in PHP. By using PHP functions we can easily implement image compression.

To improve the website loading speed image should be compressed. So we can use the above technique to compress an image before uploading the image.


$imagename = $_FILES[‘upload_image’][‘name’];
$allowed_extension = array(‘png’,’jpeg’,’jpg’);
$path = “uploads/”.$imagename ;
$extension = pathinfo($location, PATHINFO_EXTENSION);

if(in_array($allowed_extension,$extension )){
//Compress Image Code
compressImage($_FILES[‘upload_image’][‘tmp_name’],$path ,70);
echo “Invalid file type.”;

// Compress image
function compressImage($source, $destination, $quality) {
$info = getimagesize($source);
if ($info[‘mime’] == ‘image/jpeg’)
$image = imagecreatefromjpeg($source);
elseif ($info[‘mime’] == ‘image/gif’)
$image = imagecreatefromgif($source);
elseif ($info[‘mime’] == ‘image/png’)
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);

<form method=’post’ action=” enctype=’multipart/form-data’>
<input type=’file’ name=’upload_image’ >
<input type=’submit’ value=’Upload’ name=’upload’>

The post How To Compress Image Size Before Uploading In PHP. appeared first on PHPFOREVER.

Flatlogic Admin Templates banner

Leave a Reply

Your email address will not be published. Required fields are marked *