High-quality images take time to load on the webpage depending on the number of images.
You can create multiple sizes of the image file when uploading and use the low and high-quality images when required.
When reducing an image size then it also decreases its quality.
The best example of this is WordPress, whenever an image file is uploaded then it will generate a different-different size of the file. Those images will use in the theme according to requirement.
In this tutorial, I show how you can compress image size while uploading with PHP.

Contents
1. HTML
Create a <input type='file'> element in <form> and submit button.
Completed Code
<form method='post' action='' enctype='multipart/form-data'> <input type='file' name='imagefile' > <input type='submit' value='Upload' name='upload'> </form>
2. PHP
Create a images directory to store image files.
Custom Function
Create a compressImage() function to compress JPEG, PNG, and GIF images.
The function takes 3 parameters –
1. Source
2. Destination
3. File quality
Call imagecreatefromjpeg($source), imagecreatefromgif($source), and imagecreatefrompng($source) to create a new image according to $info['mime'] value.
Execute imagejpeg() method to store image to the destination. Here, the third parameter quality is optional. It takes value from 0 – 100 and the default value is 75.
Form submit
Set location to images directory and check file extension. If it is valid then call compressImage() function where pass $_FILES['imagefile']['tmp_name'],$location, and 60.
Completed Code
<?php
if(isset($_POST['upload'])){
// Getting file name
$filename = $_FILES['imagefile']['name'];
// Valid extension
$valid_ext = array('png','jpeg','jpg');
// Location
$location = "images/".$filename;
// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// Check extension
if(in_array($file_extension,$valid_ext)){
// Compress Image
compressImage($_FILES['imagefile']['tmp_name'],$location,60);
}else{
echo "Invalid file type.";
}
}
// Compress image
function compressImage($source, $destination, $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, $destination, $quality);
}
?>
3. Conclusion
In the example, I stored only the compressed image, not the original size image. You can store both the version of images while uploading.
Adjust the image quality when reducing size.
If you found this tutorial helpful then don't forget to share.
Again great post 🙂
Love your basic and logic approach to simple solutions.
How to remove black background from the Compress Image(PNG format)
As far as I know you can not change colors
But it is possible to change the color of images with the imagecreate function (for example, Captcha)
thanks very much
its code work only 1 time
Is it compressing an image before uploading file? I want to know this because we have limited bandwidth on vessel. I need some solution, which compress images and saves the traffic.
Thanks a lot,It saves my searching time and it is simple and to mark solution
Thank you so much, Yogesh! Exactly what I was looking for and easier than expected! Bookmarked! I just wish, it could compress the image without loosing quality for the web.
Is there any way to specify the size of file to be uploaded.
Like I want the uploaded file to be of 500kb only no matter whatever be the size
Yeah but what about downloading the compressed file how can i do that ?
thank you
i tried your code but portrait image position is turn landscape after upload image.
how it will solve?
i come here second times just to say, thank you..
Warning: imagejpeg() expects parameter 1 to be resource, null given in
i am getting this error
Thank you so much. I was looking for such code.
Thanks a lot sir!
You just made my day, sir. I am developing a music sharing site with chat capability and posts which includes images and videos. I must give you credits on my project. I will notify you when it’s done. Hope to go live in October. Thanks
Ps. I used the compressImage() for my image uploads, can I modify it to compress videos and audio?
Just have to give you a huge thank you! Now users can upload 8mb PNG images and it gets down to 300kb without losing too much quality. Much appreciated, thanks!
Thank you very much!
”
Fatal error: Uncaught Error: Call to undefined function imagecreatefromjpeg() in C:\xampp\htdocs\clients\index.php:40 Stack trace: #0 C:\xampp\htdocs\clients\index.php(27): compressImage(‘C:\\xampp\\tmp\\ph…’, ‘images/20201227…’, 60) #1 {main} thrown in C:\xampp\htdocs\clients\index.php on line 40″
am getting that error some functions are undefined
Great sir, i don’t know where to add the code.
A big thank you for this code and these clear explanations.
Could we add a rule to reduce the size of the images while keeping the height to width ratio?
Example:
I have a 4000×4000 image of 4 mega
With your example we reduce the weight of the images so that the image reaches 2 mega.
If we add a rule to divide the dimension in 2000×2000 before going into the code to reduce, we should be able to reduce the weight even more?
Is it possible?
Thanks a lot for your help.
I’m developing a WordPress plugin. Have tried using this code a lot, no response. Do we need to add a DB connection as well? Or can it run without it. Also, I replaced this code with the basic code of file upload in PhP. Am I doing it right? Please reply.
Thank you!