All about PHP/MySQL

Friday, March 14, 2008

Function to resize images in PHP

Very easy and useful function to resize images (of png,gif and jpg extensions) in php. I do use it often in my scripts to make the task easier.

function Resize_File($file, $directory, $max_width = 0, $max_height = 0)
{
global $config;

$full_file = $directory.$file;

if (eregi("\.png$", $full_file))
{
$img = imagecreatefrompng($full_file);
}

if (eregi("\.(jpg|jpeg)$", $full_file))
{
$img = imagecreatefromjpeg($full_file);
}

if (eregi("\.gif$", $full_file))
{
$img = imagecreatefromgif($full_file);
}

$FullImage_width = imagesx($img);
$FullImage_height = imagesy($img);

if (isset($max_width) && isset($max_height) && $max_width != 0 && $max_height != 0)
{
$new_width = $max_width;
$new_height = $max_height;
}
elseif (isset($max_width) && $max_width != 0)
{
$new_width = $max_width;
$new_height = ((int)($new_width * $FullImage_height) / $FullImage_width);
}
elseif (isset($max_height) && $max_height != 0)
{
$new_height = $max_height;
$new_width = ((int)($new_height * $FullImage_width) / $FullImage_height);
}
else
{
$new_height = $FullImage_height;
$new_width = $FullImage_width;
}

$full_id = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($full_id, $img, 0, 0, 0, 0, $new_width, $new_height, $FullImage_width, $FullImage_height);


if (eregi("\.(jpg|jpeg)$", $full_file))
{
$full = imagejpeg($full_id, $full_file, 100);
}

if (eregi("\.png$", $full_file))
{
$full = imagepng($full_id, $full_file);
}

if (eregi("\.gif$", $full_file))
{
$full = imagegif($full_id, $full_file);
}

imagedestroy($full_id);
unset($max_width);
unset($max_height);
}

Usage:
Below is a little example of its usage.

Resize_File("original.jpg", 'images/', 100, 75);

It will set the size of 'original.jpg', which exists in 'images' folder, to 100x75.

Happy coding :-)

1 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home