This Tutorial will explain how to resize and save a jpeg image using PHP’s GD Library
Before we start, let us have a look at the 5 GD library functions which we will be using in this tutorial
1. ‘getimagesize’ – to get the width and height dimensions of the source image
2. ‘imagecreatefromjpeg’ – to get the source image
3. ‘imagecreatetruecolor’ – to create the true color image to store the resized image
4. ‘imagecopyresampled’ – to generate the resized image
5. ‘imagejpeg’ – to save the output image
So lets get started
First we will get the image and its dimension values
$filename = "input.jpg";
$source = imagecreatefromjpeg($filename);
list($width, $height) = getimagesize($filename);
Now suppose we want to resize the image to 1/5th of the actual size, then we will calculate the new dimensions as
$newwidth = $width/5;
$newheight = $height/5;
You can have your own calculations to suit your requirements
Now we will create a new true color image with the calculated size and store the sampled image into it
$destination = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
And finally we will save the image
imagejpeg($destination, "output.jpg", 100);
where output.jpg is the name of the resized file and 100 is the quality of the image
The Final code looks as below
$filename = "input.jpg";
$source = imagecreatefromjpeg($filename);
list($width, $height) = getimagesize($filename);
$newwidth = $width/5;
$newheight = $height/5;
$destination = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($destination, "output.jpg", 100);