Image resizing

Image resizing

The first step in resizing images is to get the original height and width of the image. PHP comes with three functions for this: getimagesize(), imagesx() and imagesy(). The first function doesn’t require the GD library, and the latter two do.

We won’t be using the getimagesize() function, since we’re already using the GD library, which means it makes more sense to use the other two functions. The example below demonstrates the functions:

Now that we have the height and width of the image we can resize it, and make it bigger or smaller. PHP comes with two functions to do this: imagecopyresize() and imagecopyresampled(). The first function simply resizes the image, whilst the second function will resize but also resample the image. This means that the second function will create a resized image that looks much better.

The example below demonstrates the use of the imagecopyresampled() function:
<?php

// Load image
$image = open_image(’flower.jpg’);
if ($image === false) { die (’Unable to open image’); }

// Get original width and height
$width = imagesx($image);
$height = imagesy($image);

// New width and height
$new_width = 150;
$new_height = 100;

// Resample
$image_resized = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Display resized image
header(’Content-type: image/jpeg’);
imagejpeg($image_resized);
die();

?>

In the example above we first get the original width and height of the image, just like we did in the previous example. We then make up a new width and height, and in this example we used fixed values (150, 100), but in a minute we’ll see how to calculate it dynamically.

Leave a Reply


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.