PHP: Resize an image (using GD)[25 Jul 2011]
This page shows how to resize an image using the PHP GD library. Giving an alternative you can use for instance ImageMagick.
Install GD
First of all, be sure that the GD library - for image manipulation - is installed. In Debian Linux you can easily verify it with something like
$ dpkg -l | grep php | grep gd
or, for example, in Debian 6.0
$ dpkg -l php5-gd
A valid alternative is asking to PHP about GD. Just write a simple script with:
<?php var_dump(gd_info()); ?>
If GD is not installed, PHP will raise and error like
Fatal error: Call to undefined function gd_info() in /my/file.php at line xy
alternatively you will get something like
array(12) { ["GD Version"]=> string(3) "2.0" ["FreeType Support"]=> bool(true) ["FreeType Linkage"]=> string(13) "with freetype" ["T1Lib Support"]=> bool(true) ["GIF Read Support"]=> bool(true) ["GIF Create Support"]=> bool(true) ["JPEG Support"]=> bool(true) ["PNG Support"]=> bool(true) ["WBMP Support"]=> bool(true) ["XPM Support"]=> bool(false) ["XBM Support"]=> bool(false) ["JIS-mapped Japanese Font Support"]=> bool(false) }
My script
The following lines are very simple stuff, just to show the basics of the resizing process.
<?php
//set paths:
$src = "my_file_to_resize.jpg";
$dest = "resized_file.jpg";
//get image information
list($width, $height) = getimagesize($src);
//compute new image dimensions
$resize_rate = .3;
$new_width = $width * $resize_rate;
$new_height = $height * $resize_rate;
// create a new blank image
$thumb = imagecreatetruecolor($new_width, $new_height);
//open the source file (the original one to resize)
$source = imagecreatefromjpeg($src);
//resize $source saving it into $thumb
imagecopyresized($thumb, $source,
0, 0, 0, 0,
$new_width, $new_height,
$width, $height);
//save the result to file
imagejpeg($thumb, $dest);
?>
Some notes
- first of all, the process above is for jpeg images only. Check out the PHP references for the analogous functions for bmp, gif and png files;
- the script above is missing of every file check. For instance you should everytime check if:
- your source file is an image (you can use the getimagesize() function);
- if it's a non-empty pic (width or height not zero);
- if the desired new dimensions are not greater than the original ones;
- if you set to 0 one of $new_width or $new_height, imagecopyresized() will resize the setted dimension to the new value and the other one proportionally, keeping the width/height rate constant.
