Friday 3 August 2012

Image Resize

Image Resize Function :
With the help of this function we can resize our image, we just need to pass five parameter in this function. original size of image, height width of image which you want and image type exp(jpg, png, gif) etc.


function resizeImage($originalImage,$toWidth,$toHeight,$path,$arr) {
ini_set("memory_limit", "500M");
$imgType = $arr['type'];
// Get the original geometry and calculate scales
list($width, $height) = getimagesize($originalImage);
if($width < $toWidth){
$toWidth = $width;
}
if($height < $toHeight){
$toHeight = $height;
}
if($toWidth != 0){
$xscale=$width/$toWidth;}
if($toHeight != 0){
$yscale=$height/$toHeight;}
// Recalculate new size with default ratio
if ($yscale>$xscale){
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
}
else
{
$new_width = round($width * (1/$xscale));
$new_height = round($height * (1/$xscale));
}

// Resize the original image

$imageResized = imagecreatetruecolor($new_width, $new_height);
if ($imgType =="image/gif"){
$imageTmp = imagecreatefromgif($originalImage);

$background = imagecolorallocate($imageResized, 0, 0, 0);
            ImageColorTransparent($imageResized, $background);

imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagegif($imageResized, $path);
}
elseif($imgType =="image/png" || $imgType =="image/x-png")
{
$imageTmp = imagecreatefrompng($originalImage);

imagealphablending($imageResized, false);
            imagesavealpha($imageResized, true);
       $background = imagecolorallocatealpha($imageResized, 255, 255, 255, 127);
            imagecolortransparent($imageResized, $background);

imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagepng( $imageResized,$path);
}
else {
$imageTmp  = imagecreatefromjpeg($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($imageResized,$path);
}
return $imageResized;
}


No comments:

Post a Comment