Automated Image Resizing With PHP

Automated Image Resizing With PHP

After working on a few projects (including the site you are viewing now), it came to clear in my mind that the need for the script to handler automatic image resizing is absolutely necessary. I have beening thinking about it when I was building the photo gallery for this website, I found some useful functions from, however, I was unable to run those functions from my development environment. Until now I realise that in order to make the image functions working with PHP, the PHP has to be compiled with GD library and JPEG-support. The following code will assume that you have PHP supported by GD library and JPEG. Firstly we will need to read from an image. To read from an image file, you need to use function imagecreatefromjpeg and pass a filename as argument:
$src = imagecreatefromjpeg( $filename );
To read from an image binary data, you need to use function imagecreatefromstring and pass image binary data as argument:
$src = imagecreatefromstring( $image_data );
In either case, the returned value $src will be a PHP resource type and can be referenced later. Now you need to tell the script the size of the new image going to be. In this article I will only resize the image based on height, you can change the script accordingly if you want to resize the based on image width.
$size = 60;
$width = imagesx( $src );
$height = imagesy( $src );
$aspect_ratio = $height / $width;
Function imagesx and imagesy will give us the actual images width and height respectively. Now we can start resize the image.
// start resizing
if ( $height <= $size )
[tab]$new_w = $width;
[tab]$new_h = $height;
[tab]$new_h = $size;
[tab]$new_w = abs( $new_h / $aspect_ratio );
We are saying here that if image's original height is less than the specified size, then we don't change the image size, otherwise calculate the new width and height. Lastly we use function imagecreatetruecolor to create a new image based on the new width and height.
$img = imagecreatetruecolor ( $new_w, $new_h );
// output image
imagecopyresampled( $img, $src, 0, 0, 0, 0, $new_w, $new_h, $width, $height );
imagejpeg( $img );
Here we don't want to stretch or shrink the image, so we pass four 0s in the imagecopyresampled parameters. If you want to output the image to a file rather than display directly, pass filename as extra argument.
imagejpeg( $img, $filename );


Leave a Reply

Your email address will not be published. Required fields are marked *

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!