Compressing Image Size Using PHP

Nowadays, image size is a main concern of a website. Because,  it may reduce your website load time and as a result you can loose your potential users. If website is static then its not a tough job, because you can edit that single file which has large size. Rather you can use AI tools to compress file size like https://tinyjpg.com/

But when the site is dynamic and images are randomly uploaded by thousand users then what will you do?

Yes, today I will give you a PHP solution to overcome this situation.

How many ways to compress image:

There are lots of ways followed by the giant companies like Facebook, Google, Instagram etc. to compress their images. Following tactics are applied by them:

1. Make the image resolution pixel small.

2. Keep the pixel same but less the quality.

Based on your need you can choose any of the tricks to lower the image file size. You can do it after upload the file not before or during upload. So first upload the file in desired directory and then use that path to perform following codes:

Explanation:

If we call resize_image("img/photo.jpg", "img/resized/photo.jpg", 100, 50);

Then function will resize photo.jpg from img directory with resolution of 100px(width) X 50px(height) after cropping from raw file and save it to a new directory resized keeping the file name same.

Here if you want whatever the image size was, u want to generate an image in size of 1920X1080px then u should call the function as: resize_image("img/photo.jpg","img/resized/photo.jpg", 1920, 1080);

But here the excess portion will be filled with black background.

On the otherhand if we call the 2nd function: compressImage("img/photo.jpg", "img/compressed/photo.jpg", 9);

Then function will apply Best Compression Strategy to render photo.jpg file and save it to compressed directory.

Here quality parameter has following levels:

    0    -     NO_COMPRESSION: Keep raw file
    1    -     BEST_SPEED: Little compressed but render fast
    9    -     BEST_COMPRESSION: Compressed as much as it can but slowly render
   -1    -     DEFAULT_COMPRESSION: Apply default strategy

So, lower value means higher quality and higher value means much compression and less quality. You can apply those functions whatever your project is build, just use the source and destination path. But before testing the script make sure your GD extension is enabled in your php version.

Download the sample code

Use it and enjoy!

Share:

Leave your Comment

© 2024 Tanvir's Blog | All Rights Reserved