If you are searching for a script to compress image size in PHP without losing quality, you have found the best tutorials. Here, You will get the standard source code to implement in your project.
If you upload a large size image in your application, it will take more time to load the web page. It is not good for any web application. So, You must reduce the image size before upload.
How to Compress Images in PHP
Now, Let’s start coding to compress & reduce image quality using PHP
Learn the following examples also –
- Preview an Image before uploading using PHP
- Single Image Crud Operations using PHP & MySQL
- Create PHP Image Gallery
- Image Upload Rest Api using PHP & MySQL
1. Create a Folder Structure
Now, create a folder structure to write the following PHP script.
myproject |__uploads/ |__upload-form.php |__compress-script.php |
2. Create an HTML Form to Upload Image
The PHP code initializes a session and retrieves a message from the session, displaying it in an HTML document. The document includes a form with a file input for image selection, posting to a script named “compress-script.php” for image compression. The displayed message is cleared from the session after being shown.
File Name – upload-form.php
<?php session_start(); $msg= !empty($_SESSION['msg'])? $_SESSION['msg']:''; ?> <!DOCTYPE html> <html> <head> <title>Compress Image Size Using PHP</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <!--====image upload form===--> <?php echo $msg; unset($_SESSION['msg']); ?> <form action="compress-script.php" method="post" enctype="multipart/form-data"> <label>Select Your File</label> <input type="file" name="image"> <input type="submit" value="Compress Now" name="submit"> </form> <!-- image upload form====--> </body> </html>
Explanation –
- The PHP script initiates a session using
session_start()
to facilitate data persistence across pages for the same user. - It retrieves a message from the session variable
$_SESSION['msg']
and assigns it to the variable$msg
. If the session message is empty,$msg
defaults to an empty string. - The HTML document starts with a specified title, “Compress Image Size Using PHP,” and includes viewport settings for responsiveness on various devices.
- The PHP block echoes the session message (
$msg
) onto the HTML page. After display,unset($_SESSION['msg'])
is used to clear the session message. - An HTML form is provided for image upload, with the action set to “compress-script.php” using the POST method and
enctype="multipart/form-data"
. It includes a file input for selecting an image and a submit button labeled “Compress Now.”
3. Compress Images Script
The PHP code uploads and compresses images. It checks form submission, validates and compresses the image, and then stores success or error messages in a session variable before redirecting to the upload form.
File Name – compress-script.php
<?php // uploading files on submit if(isset($_POST['submit'])){ // uploading files $msg= upload_image(); session_start(); $_SESSION['msg']= $msg; header('location:upload-form.php'); } function upload_image(){ $uploadTo = "uploads/"; $allowImageExt = array('jpg','png','jpeg','gif'); $imageName = $_FILES['image']['name']; $tempPath=$_FILES["image"]["tmp_name"]; $imageQuality= 60; $basename = basename($imageName); $originalPath = $uploadTo.$basename; $imageExt = pathinfo($originalPath, PATHINFO_EXTENSION); if(empty($imageName)){ $error="Please Select files.."; return $error; }else{ if(in_array($imageExt, $allowImageExt)){ $compressedImage = compress_image($tempPath, $originalPath, $imageQuality); if($compressedImage){ return "Image was compressed and uploaded to server"; } else{ return "Some error !.. check your script"; } }else{ return "Image Type not allowed"; } } } function compress_image($tempPath, $originalPath, $imageQuality){ // Get image info $imgInfo = getimagesize($tempPath); $mime = $imgInfo['mime']; // Create a new image from file switch($mime){ case 'image/jpeg': $image = imagecreatefromjpeg($tempPath); break; case 'image/png': $image = imagecreatefrompng($tempPath); break; case 'image/gif': $image = imagecreatefromgif($tempPath); break; default: $image = imagecreatefromjpeg($tempPath); } // Save image imagejpeg($image, $originalPath, $quality); // Return compressed image return $originalPath; } ?>
Explanation –
- The PHP code begins by checking if the form has been submitted (
$_POST['submit']
is set). - If the form is submitted, it calls the
upload_image()
function to handle file upload and compression. - The
upload_image()
function sets the target directory for uploads, allowed image extensions, and defines variables for image information and quality. - It retrieves the uploaded image’s name, temporary path, and defines the desired quality for compression.
- The function checks if an image has been selected; if not, it returns an error message.
- If an image is selected, it validates the image type against allowed extensions. If the type is valid, it calls the
compress_image()
function. - The
compress_image()
function takes the temporary and original paths, along with the desired image quality, and compresses the image using the GD library. - The compressed image is saved to the server, and the function returns a success or error message based on the outcome.
- Session data is used to store the message, and the user is redirected back to the upload form (
upload-form.php
).
My Suggestion
I have shared the best way to compress image size using PHP. Now, you can easily implement it with different type types of images like jpg, png, gif.