How to Optimize Image before Upload Using PHP ?






Do you need to optimize an image without losing its quality? 

This guide is for you.


Just recently, one of our Customers sent us a Support request to optimize images on upload in PHP. 

If you need to maintain the quality of an image, you will need to use a so-called lossless compressor such as TIFF, PNG and so on.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to optimize their Website.

In this context, we shall look into how we can reduce or compress file size at the time of uploading it on a Website.


The facts about Image Optimization for your Website.

Images play an important role in the site speed. Heavy images slow down the page speed which in 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.

Here, you will learn how to use TinyPNG  service for optimizing website images. 

With TinyPNG, you can reduce the size of an image file without loosing its quality.


How to optimize images for WordPress?

From your WordPress dashboard, you simply Activate the plugin from your Plugins page. 

1. Go to the Settings > Compress JPEG & PNG images page and register a new account. 

2. Enter the API key you got from https://tinypng.com/developers

3. Go to Media > Bulk Optimization and optimize all your images.

Also, to automatically resize images in WordPress, simply Adjust image sizes in the Settings > Media screen.

Here you can change width and height for the thumbnail, medium, and large image sizes. 

WordPress will then automatically create scaled versions of each image using these sizes. 

You can choose which size you want to insert from the WordPress editor.


How to use TinyPNG to Optimize Website Image ?

i. To get started you need to install the TinyPNG library. 

Install the library using the command below:

composer require tinify/tinify

ii. After installing the library, get your API key from 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.

iii. Once you are ready with the API key, we will go to the coding aspect. 

Here, we will create a simple HTML form that contains file input and a submit button as seen below:

<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>

The above HTML form will enable you to upload an image. The code presented below will help to move the uploaded image on 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";
}

In order to optimize images, you just need to add 2 lines of code after the move_uploaded_file statement as per below:

// To optimize image using TinyPNG
$source = \Tinify\fromFile(getcwd().'/uploads/'.$src_file_name);
$source->toFile(getcwd().'/uploads/'.$src_file_name);

The above lines of code will 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.

Then, the 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>

Now you can give it a try and you will see the optimized version of the image stored into your working directory as per your Website project.


[Need urgent assistance to develop your Laravel Website? We are available to help you today. ]


Conclusion

This article will guide you on how to #optimize the #image on upload in #PHP. #TinyPNG uses smart lossy compression techniques to reduce the file size of your PNG files. By selectively decreasing the number of colors in the image, fewer bytes are required to store the data. The effect is nearly invisible but it makes a very large difference in file size.

To optimize images for the web:

1. Name your images descriptively and in plain language.

2. Optimize your alt attributes carefully.

3. Choose your image dimensions and product angles wisely.

4. Reduce the file size of your images.

5. Choose the right file type.

6. Optimize your thumbnails.

7. Use image sitemaps.



Related Post


Keep In Touch

We hope to hear from you.

Accept File Type: jpg,jpeg,png,txt,pdf,doc,docx