Thread: PHP resizer
View Single Post
  #1  
Old 08-25-2008, 11:29 AM
Sakari Sakari is offline
Member
 
Join Date: Jul 2008
Posts: 34
Sakari is on a distinguished road
Default PHP resizer

Hi



Resizing an image in PHP and maintaining its aspect ratio
________________________________________
A question that has been asked many times is how to resize an image in PHP while maintaining the aspect ration of the original image.

The function below does just that, it takes an image resource and the new dimensions for the image in pixels and returns the resized image.
Quote:
Code:
/**
* Resize and image while maintaining its aspect ratio.
*
* @param resource $src The image to resize.
* @param int $w The target width.
* @param int $h The target height.
* @return resource The resized image or the original image if it did not need to be scaled.
*/
function resizeImage($src, $w, $h) {

// Get the current size
$width = ImageSx($src);
$height = ImageSy($src);

// If one dimension is right then nothing to do
if($width == $w || $height == $h)
return($src);

// Calculate new size
if(($w - $width) > ($h - $height)) { // use height
$s = $h / $height;
$nw = round($width * $s);
$nh = round($height * $s);
}
else { // Use width
$s = $w / $width;
$nw = round($width * $s);
$nh = round($height * $s);
}

// Resize to correct size
$im = ImageCreateTrueColor($nw, $nh);
ImageCopyResampled($im, $src, 0, 0, 0, 0, $nw, $nh, $width, $height);

// Return the new image
return($im);
}
A simple example to load, resize and send an image to the browser would be:
Code:
$image = ImageCreateFromJPEG('images.jpg');
$image = resizeImage($image, 400, 400);
header("Content-Type: image/jpeg");
ImageJPEG($image, '', 80);

thanks
__________________
web design services
Free Templates
Reply With Quote
 #Add to Ads's Reputation  
OldSponsored Ads
Ads AdsPromoter is online
Member
 
Join Date: LongTime
Posts: 1100
Ads is on a distinguished road
Default New Sponsored Ads



This message will go away once you are registered. Also, by registering, you will have access to all post topics, communicate privately with other members (PM), respond to polls, upload graphics, and access other special features! Registration is fast, simple and absolutely free so please Click Here to join our Web Hosting community today!
Reply With Quote