Resize image

This algorithm is especially useful when you want to resize an image down to the maximum size possible inside a defined maximum width and maximum height, while maintaining the images dimensions.

The function accepts a php $_FILES array variable (as is created when an image is uploaded) image as a parameter. So if your HTML file form element was named “upload_image”, then you can pass $_FILES['upload_image'] to this function provided that the file was an image.

It will scale down the image passed to it based on the $MAX_HEIGHT and $MAX_WIDTH variables you can define at the top of the function (size in pixels).

The last part of the function creates a new image resource as the new scaled down version of the original image and returns it.

<?php
function make_thumb($image_resource)
{
$MAX_HEIGHT = 150; //pixels
$MAX_WIDTH = 100; //pixels

/*work out the new image dimensions*/
$imgsize = getimagesize($image_resource['tmp_name']);
$orig_height = $imgsize[1];
$orig_width = $imgsize[0];

$width_divider = $orig_width / $MAX_WIDTH;
$height_divider = $orig_height / $MAX_HEIGHT;

$temp_height = $orig_height / $width_divider;

$use_divider = $width_divider;
if($temp_height > $MAX_HEIGHT)
$use_divider = $height_divider;

$new_height = floor($orig_height / $use_divider);
$new_width = floor($orig_width / $use_divider);

/*create a new instance of the resized image*/ $new_image = imagecreatetruecolor($new_width, $new_height);
$old_img = imagecreatefromjpeg($image_resource['tmp_name']);
imagecopyresampled($new_image, $old_img,0,0,0,0, $new_width, $new_height, $orig_width, $orig_height);

return $new_image;
}
?>
Comments (0)
+ –