Magento: Function to resize any image

In this article I'm writing code for resize any image in magento according to your desire width and height. In this article, I’ll describe how to resize images, such as needing to resize a custom image and display it on the site in special sized areas. Let’s do it.
Put below function in any helper file of your module. And call that helper function in any template file to resize any image.

/**
* $imageName    name of the image file
* $width        resize width
* $height        resize height
* $imagePath    the path where the image is saved.    (must be inside ‘media’ directory)
* return        full url path of the image
*/

public function resizeImage($imageName, $width=NULL, $height=NULL, $imagePath=NULL)
{
$imagePath = str_replace("/", DS, $imagePath);
$imagePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $imageName;

if($width == NULL && $height == NULL) {
$width = 100;
$height = 100;
}
$resizePath = $width . 'x' . $height;
$resizePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $resizePath . DS . $imageName;

if (file_exists($imagePathFull) && !file_exists($resizePathFull)) {
$imageObj = new Varien_Image($imagePathFull);
$imageObj->keepAspectRatio(TRUE);
$imageObj->keepFrame(TRUE);
$imageObj->keepTransparency(TRUE);
$imageObj->constrainOnly(TRUE);
$imageObj->backgroundColor(array(255, 255, 255));
$imageObj->quality(90);
$imageObj->resize($width,$height);
$imageObj->save($resizePathFull);
}

$imagePath=str_replace(DS, "/", $imagePath);
return Mage::getBaseUrl("media") . $imagePath . "/" . $resizePath . "/" . $imageName;
}

Here,

$imageName is the name of the image (e.g. imagename.jpg)

$width is the image resize width (e.g. 150)
$height is the image resize height (e.g. 150)

$imagePath is the path where the image is stored/saved. This directory must be inside ‘media’ directory. Like, if we specify ‘xyz/image‘ as $imagePath then our image path must be ‘media/xyz/image/imagename.jpg‘ (the $imageName is imagename.jpg)

For Example:-

<img src=”<?php echo Mage::helper(‘moduleName’)->resizeImage(‘imagename.jpg’, 150, 150, ‘foldername’); ?>” alt=”resized image” />

Image will saved in ROOT FOLDER/media/foldername/150*150/imagename.jpg.

Hope this post helps you.