How to Compress Image Size Using PHP Before Uploading.


In this tutorial we learn how to compress image using PHP. This technique is used to optimize the image while uploading. To improve the website loading speed image should be compressed, the large size may take more time to upload to a server and space as well, it also takes more time to load page. It is good practice to minimize the image size before uploading through your website.


Here we create html form where we will upload our image.

<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="image" accept="*">
    <input type="submit" value="Upload" name="submit_photo">

Now we add PHP code line in the same index.php file.

       // Getting file name
       $imagename = $_FILES['image']['name'];
       // Valid extension
       $valid_ext = array('png','jpeg','jpg','gif');
	 $imageExtention = @end(explode('.', $imagename)); // explode the image name to get the extension
     $imagetest1 = strtolower($imageExtention);
     $new_image = time().'.'.$imagetest1;
       //move image to a location
      $location = "../uploads/gallery/".$new_image;

$sql="INSERT INTO gallery (image) VALUES (:photos)";


   if ($LastInsertId>0) {
 echo '<script>alert("Photo has been added.")</script>';
echo "<script>window.location.href ='index.php'</script>";
         echo '<script>alert("Something Went Wrong. Please try again")</script>';

       // file extension
       $file_extension = pathinfo($location, PATHINFO_EXTENSION);
       $file_extension = strtolower($file_extension);

       // Check extension

            // Compress Image,
			//NB youcan use number, for jpeg or gif and jpg, it should be 0-100 
			//for png it should be 0 to 9

			 echo '<script>alert("File format is not correct.. Please try other")</script>';

    // Compress image
    function compressedImage($source, $path, $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, $path, $quality);



Finary you can test your project.

Other Recommended for you

  • .What is Cloud Firestore? Android Studio
  • .Firebase Realtime Database vs Firestore.
  • .What is an Intent in Android? Types of Intent
  • .What is Firebase?