Re-sampling Image In PHP

When a user uploads a high quality image, you might have to reduce the image size or re-sample to show it in smaller screens or as thumbnails so the loading time can be reduced.

The below code will help you generate a copy of the original image in the destination folder and dimensions you specify.


//FUNCTION TO REDUCE IMAGE SIZE
function reduce_image_size($destination,$image_name,$files)
{
//REDUCE IMAGE RESOLUTION
if($files)
{
$dest = $destination.$image_name;
$width = 300; //in pixels
$height = 300;
list($original_width, $original_height) = getimagesize($files);
$original_ratio = $original_width/$original_height;
if ($width/$height > $original_ratio)
{
$width = $height*$original_ratio; //To maintain the aspect ratio
}
else
{
$height = $width/$original_ratio;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($files);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $original_width, $original_height);
imagejpeg($image_p,$dest, 100);
ImageDestroy ($image_p);
}
//END OF REDUCING IMAGE RESOLUTION
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s