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.

Related Posts

forest fire

Forest Fire – Techgig, All testcases passed. Challenge #1

Forest Fire (100 Marks) Challenge 1: Forest fire You are camping in a forest area at night. You are living with the forest officers to experience their challenges…

the magic wand

The Magic Wand – TechGig PHP answer, all test cases passed. Challenge #2

The Magic Wand – TechGig PHP answer – all testcases passed The Magic Wand (100 Marks) You are a wizard who possesses the magic wand that can be…

PHP interview Questions and Answers

What is PHP? Answer: PHP stands for Hypertext Preprocessor. It is a widely used server-side scripting language primarily designed for web development. PHP code is embedded within…

install php

A Step-by-Step Guide on How to Install PHP

Install PHP : A Step-by-Step Guide on How to Install PHP Introduction: PHP is a widely used server-side scripting language that powers countless websites and web applications….

what is php

What is PHP? Understanding PHP: The Powerhouse of Web Development

Introduction: What is PHP? Understanding PHP: The Powerhouse of Web Development: In the world of web development, PHP stands tall as one of the most widely-used and…

php form

Complete Php form example

Here we are going to check how to create a php form and insert its values to database table. In this example we will be submitting the…

This Post Has 3 Comments

Leave a Reply

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