🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

How to Upload and Compress an Image using PHP

Image compression is very helpful to reduce the size of the image. Generally, the user does not optimize the image when uploading through the website. In this case, compress images before upload to optimize the image.

So, now I am show you how to compress image before upload using PHP.

Create a PHP form with an input field and submit button. This <form>
tag contain following contain:

  • method=”post”
  • enctype=”multipart/form-data

Note: enctype=”multipart/form-data” is compulsory for image upload precess via post method in form.

index.php

<?php include 'upload.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Compress Image</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:20px;">
<div class="panel panel-primary">
<div class="panel-heading text-center"><strong>Image Upload and Compress using PHP</strong></div>
<div class="panel-body">
<div class="row">
<div class="col-sm-8">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label><b>Select Image File:</b></label>
<input type="file" class="form-control-file border" name="image">
</div>
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Compress Image">
</form>
</div>
<div class="result">
<?php if(!empty($compressedImage)){ ?>
<p><b>Original Image Size:</b><?php echo $imageSize; ?> </p>
<p><b>Compressed Image Size:</b><?php echo $compressedImageSize; ?></p>
<img src="<?php echo $compressedImage; ?>">
<?php } ?>
</div>
</div>
</div>
</div>
</body>
</html>
view raw index.php hosted with ❤ by GitHub

After the form submission, the file data is submitted to the upload.php file for further processing. Then, compress and upload images in PHP.

The upload.php file handles the image compression upload operations. I have used some PHP image functions like compressImage() that helps to compress and save image on the server using PHP.

If the file is submitted, then retrieve the file info using the PHP $_FILES method, compressed size, and upload image using compressImage() function. Then see the image upload status.

upload.php

<?php
/*
* Custom function to compress image size and
* upload to the server using PHP
*/
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;
}
// 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"];
$imageSize = $_FILES["image"]["size"];
// Compress size and upload image
$compressedImage = compressImage($imageTemp, $imageUploadPath, 75);
if($compressedImage){
$compressedImageSize = filesize($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.';
}
}
// Display status message
echo $statusMsg;
?>

Then, see the results:

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.