Compress and upload Image using PHP

compress and upload image
PHP

Compress and upload Image using PHP

How to compress and upload image using Php?

Uploading large sized files will always take more time and also it will occupy more disk space. To solve this issue better option is reducing the image size and then upload it. Go through the tutorial for compress and upload image using php.

HTML :

<!DOCTYPE html>
<html>
<head>
	<title>Image Compress</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
	<div class="row">
		<div class="col-md-4">
			<form action="imageupload.php" method="post" enctype="multipart/form-data">
				<div class="form-group">
					<label>Select Image File:</label>
			    	<input type="file" name="image" class="form-control">
				</div>
			    <input type="submit" name="submit" value="Upload" class="btn btn-sm btn-info">
			</form>
		</div>
	</div>
	
</body>
</html>

Declare a form with file input and submit form.

Linked bootstrap css to do some basic designs, link is attached below.

Bootstrap Css : https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

PHP :

<?php 
// File upload path 
$uploadPath = "uploads/"; 
 
// If file upload form is submitted 
$status = $statusMsg = ''; 
if(isset($_POST["submit"])){ 
    $status = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        // File info 
        $fileName = basename($_FILES["image"]["name"]); 
        $imageUploadPath = $uploadPath . $fileName; 
        $fileType = pathinfo($imageUploadPath, PATHINFO_EXTENSION); 
         
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            // Image temp source 
            $imageTemp = $_FILES["image"]["tmp_name"]; 
             
            // Compress size and upload image 
            $compressedImage = compressImage($imageTemp, $imageUploadPath, 75); 
             
            if($compressedImage){ 
                $status = 'success'; 
                $statusMsg = "Image compressed successfully."; 
            }else{ 
                $statusMsg = "Image compress failed!"; 
            } 
        }else{ 
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $statusMsg = 'Please select an image file to upload.'; 
    } 
} 

function compressImage($source, $destination, $quality) 
{ 
    // Get image info 
    $imgInfo = getimagesize($source); 
    $mime = $imgInfo['mime']; 
     
    // Create a new image from file 
    switch($mime){ 
        case 'image/jpeg': 
            $image = imagecreatefromjpeg($source); 
            break; 
        case 'image/png': 
            $image = imagecreatefrompng($source); 
            break; 
        case 'image/gif': 
            $image = imagecreatefromgif($source); 
            break; 
        default: 
            $image = imagecreatefromjpeg($source); 
    } 
     
    // Save image 
    imagejpeg($image, $destination, $quality); 
     
    // Return compressed image 
    return $destination; 
} 

echo $statusMsg; 
?>
  1. Define the upload path
  2. If form submitted, check $_FILES[“image”][“name”] is empty or not
    1. if empty, show eror message indicating upload a file
    2. If not empty,
      1. get the basename to filename
      2. set the upload path
      3. get the image extension to check whether it is allowed or not
      4. if allowed type call the compressImage() to compress image. Pass image details as parameter.
  3. compressImage()
    1. get size of image by getimagesize()
    2. get the image mime type
    3. create a new image by passing the source to imagecreatefromjpeg() function. imagecreatefromjpeg() function will create a new image from url.
    4. imagejpeg() will output image to browser or file

You can do the compress and upload image for multiple image upload also, you have to call this function while uploading the files. To check how to multiple files at a time check this link Multiple file upload .

Hope this tutorial for compress and upload image using php will help you.

3 thoughts on “Compress and upload Image using PHP

Leave a Reply

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

Back To Top