Image Resizing or Compressing with PHP

 

One of the challenges that comes with maintaining a graphic-intensive website like social networking websites is finding a way to get high quality images throughout the site with as little effort as possible.

This tutorial teaches you how to design a system where you can easily resize or compress the image files that you have already uploaded to your server using PHP.

The major advantage of this system is that it allows you to resize and crop any image on your website without touching the actual image or writing any code. 

The system is made up of two functions, one of the function scans and gets all the image files in a given directory and then passes those image files to the second function that does the resizing/compressing of the image files to your desired sizes.

The resizing/compressing of the image files are done depending on the aspect ratio of the file. The aspect ration of each file is calculated using the original width and height of the image file.

To resize or compress image files, you only need to open a file named configuration.php and set up the following:


CONFIGURATION FILE:

<?php 

/*  
*This is the parent directory where all the files you want to resize,  
* including the sub-directories and the files in them are all located  
*/ 
define('UPLOADED_FILES_BASE_DIRECTORY', 'uploads'); 

/*  
* This is the width that all the resized files will have depending on their aspect ratio 
*/ 
define('RESIZE_FILES_TO_width', '100'); 


/*  
* This is the height that all the resized files will have depending on their aspect ratio 
*/ 
define('RESIZE_FILES_TO_height', '100'); 


// Aspect ration of each file is calculated using the width and height of the file 
?> 


Before a file can be resized or compressed, the system will first of all check the original size (width/height) of the image file comparing this size to your given size (width/height), if your given size are greater than the original size of the file, the system will compress the file using the original size of the file to maintain the aspect ratio of the file but if your given size are less than the original size of the file then the system will compress the file using your given size.

Features of the System:

1. Scans a given directory to get all the available image files in the directory
2. Resizes JPEGs, GIFs, and PNGs image files to new image dimensions, while still keeping the aspect ratio of the file
3. Intelligently sharpens for crisp photos at any size
4. Resize by exact width/height
5. Resize by width - exact width will be set, height will be adjusted according to aspect ratio - (landscape)
6. Resize by height - like Resize by Width, but the height will be set and width adjusted dynamically - (portrait)
7. Auto determine options 2 and 3. If you're looping through a folder with different size photos, let the script determine how to handle this
8. Resize, then crop, no image distortion