How to Resize Any Images in Magento
Nick Kravchuk Avatar

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.Say we have an image located in the media folder /media/example.jpg
First, we need to initialize the $folderURL variable:

$folderURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);

Then, the image URL:

$imageURL = $folderURL . $fileName;

Note: The format for $fileName = can be: ‘example.jpg’; or ‘testfolder/example.jpg’;
Next, we need to specify the full path for the existing file name ($basePath) and the name of the file that needs to be resized ($newPath). In this case they are:

$basePath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . $fileName;
$newPath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . "resized" . DS . $fileName;

After this, we need to create an instance of Varien_Image class

//$basePath - origin file location
$imageObj = new Varien_Image($basePath);
$imageObj->constrainOnly(TRUE);
$imageObj->keepAspectRatio(FALSE);
$imageObj->keepFrame(FALSE);
//$width, $height - sizes you need (Note: when keepAspectRatio(TRUE), height would be ignored)
$imageObj->resize($width, $height);
//$newPath - name of resized image
$imageObj->save($newPath);

Then, we need to get the URL of the resized image:

$resizedURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . "resized" . DS . $fileName;

Lastly, let’s make the function resizeImg($fileName, $width, $height = ”)

public function resizeImg($fileName, $width, $height = '')
{
    $folderURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
    $imageURL = $folderURL . $fileName;

    $basePath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . $fileName;
    $newPath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . "resized" . DS . $fileName;
    //if width empty then return original size image's URL
    if ($width != '') {
        //if image has already resized then just return URL
        if (file_exists($basePath) && is_file($basePath) && !file_exists($newPath)) {
            $imageObj = new Varien_Image($basePath);
            $imageObj->constrainOnly(TRUE);
            $imageObj->keepAspectRatio(FALSE);
            $imageObj->keepFrame(FALSE);
            $imageObj->resize($width, $height);
            $imageObj->save($newPath);
        }
        $resizedURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . "resized" . DS . $fileName;
     } else {
        $resizedURL = $imageURL;
     }
     return $resizedURL;
}

That’s it! I hope this article helps you. Until next time, Happy Coding!

You may also want to read: