Recently one of the readers asked me how to optimize images on upload in PHP. To answer the question, I decided to write an article that will show how we can reduce or compress file size at the time of uploading it.
As a developer file uploading is our regular task. We always do it in a traditional way. Using the built-in function move_uploaded_file
we move the images to the directory and leave them as it is. Do we think on a few points like what is the size of the uploaded image? Will this image take time to load on a website? Can I optimize an image without losing its quality?
Images play an important role in the site speed. Heavy images slow down the page speed which as a result loses your audiences and traffic. This situation is not affordable. We take a lot of effort to build the audience and traffic. So as a good practice, you should optimize the image while uploading.
In this article, I am going to use the TinyPNG service for optimizing the images. We will write a code for it in moments. Meanwhile, below is the screenshot from tinypng.com to visualize the difference between the original and optimized image.
Use TinyPNG to Optimize Image On Upload
To get started you need to install the TinyPNG library. Install the library using the command below.
composer require tinify/tinify
After installing the library, get your API key from the TinyPNG website.
Note: TinyPNG allows compressing 500 images free per month. For more than 500 images you need to pay them. If you are running a small website then this quota is enough.
Once you are ready with the API key, let’s start with the code. I am creating a simple HTML form that contains file input and a submit button.
<form method="post" enctype="multipart/form-data">
<p><input type="file" name="myfile" accept="image/*" required /></p>
<button type="submit" name="submit">Submit</button>
</form>
When the users upload an image using this form, developers write the below kind of code to move the uploaded image to the server.
if (isset($_POST['submit'])) {
$allowed_mime_types = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
if (!in_array($_FILES['myfile']['type'], $allowed_mime_types)) {
echo 'Invalid file format.';
exit();
}
if (!file_exists(getcwd().'/uploads')) {
mkdir(getcwd().'/uploads', 0777);
}
$src_file_name = $_FILES['myfile']['name'];
move_uploaded_file($_FILES['myfile']['tmp_name'], getcwd().'/uploads/'.$src_file_name);
echo "File uploaded successfully";
}
The above code is correct and there is no issue in it except the missing part of the optimization of the image. For optimizing images, you just need to add 2 lines of code after the move_uploaded_file
statement.
//optimize image using TinyPNG
$source = \Tinify\fromFile(getcwd().'/uploads/'.$src_file_name);
$source->toFile(getcwd().'/uploads/'.$src_file_name);
The above 2 lines take an image from the source path, optimize it with the TinyPNG library without losing quality, and save it back to the same source path. In other words, it replaces the original image with the optimized version.
Our final code is as follows.
<?php
require_once("vendor/autoload.php");
\Tinify\setKey("TINYPNG_API_KEY"); //pass your actual API key
if (isset($_POST['submit'])) {
$allowed_mime_types = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
if (!in_array($_FILES['myfile']['type'], $allowed_mime_types)) {
echo 'Invalid file format.';
exit();
}
if (!file_exists(getcwd().'/uploads')) {
mkdir(getcwd().'/uploads', 0777);
}
$src_file_name = $_FILES['myfile']['name'];
move_uploaded_file($_FILES['myfile']['tmp_name'], getcwd().'/uploads/'.$src_file_name);
//optimize image using TinyPNG
$source = \Tinify\fromFile(getcwd().'/uploads/'.$src_file_name);
$source->toFile(getcwd().'/uploads/'.$src_file_name);
echo "File uploaded successfully.";
}
?>
<form method="post" enctype="multipart/form-data">
<p><input type="file" name="myfile" accept="image/*" required /></p>
<button type="submit" name="submit">Submit</button>
</form>
Go ahead and give it a try to it. You should see the optimized version of the image get stored in your directory.
I hope you understand how to optimize the image on upload in PHP. I would like to hear your thoughts and suggestions in the comment section below.
Related Articles
- TinyPNG Compress Images Using PHP
- Upload and Compress Multiple Images in PHP
- A Guide Tto Upload and Compress Images in Laravel
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
Nice article
Simply great 😉
got reduction on my jpg images by 50% with almost no quality loss.
OsclassPoint.com
Please I will like to ask how to implement this but I dont know how to
Please refer my video to the same topic on YouTube https://www.youtube.com/watch?v=OZDxPMu61xw