Use PHP GD to Resize Images on Upload

PHP GD Lib is a library used to manipulate images directly on a server. It is available on all Hosting.com Platform Services running Linux.

Installation

On Red Hat or CentOS servers it can be installed with:

yum install php-gd

On Ubuntu use:

apt-get install php5-gd

Example Code Usage for Jpeg Images

Create an image resource.

$im = ImageCreateFromJpeg('/path/to/imagefile.jpg');

Find the original height and width.

$ox = imagesx($im);
$oy = imagesy($im);

Now we will determine the new height and width. For this example maximum height will be 375px and the width will be 500px. To prevent inproper proportions we need to know if the image is portrate or landscape then set one dimension and caluate the other. 

$height = 375;
$width = 500;
if($ox < $oy)   #portrate
    {
       $ny = $height;
       $nx = floor($ox * ($ny / $oy)); 
    } 
else #landscape
    {
       $nx = $width;
       $ny = floor($oy * ($nx / $ox)); 
    } 

Then next two functions will create a new image resource then copy the original image to the new one and resize it.

$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy);

Now we just need to save the new file.

imagejpeg($nm, '/path/to/smallerimagefile.jpg', 100);

Support for GIF images

With some minor changes the code above will work for GIF images. You will need to use ImageCreateFromGif in place of ImageCreateFromJpeg. You will also need to use imagegif in the place of imagejpeg.  

Adding a few conditions to the code will allow you to support both image types.