Saturday 27 September 2014

how to resize image in custom module in magento

 Open namespace/modulename/helper/data.php

paste following code in helper class :-

 <?php
class Namespace_Modulename_Helper_Data extends Mage_Core_Helper_Abstract
{

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->constrainOnly(TRUE);
        $imageObj->keepAspectRatio(TRUE);   //set false if you don't want set image size in ratio (like:-100x100,200x200).
        $imageObj->resize($width,$height);
        $imageObj->save($resizePathFull);
    }
            
    $imagePath=str_replace(DS, "/", $imagePath);
    return Mage::getBaseUrl("media") . $imagePath . "/" . $resizePath . "/" . $imageName;
}
}

and  use in any template/phtml file of your module:-
 

<img src="<?php echo Mage::helper('modulename')->resizeImage('imagename.jpg', 100, 100, 'path/image'); ?>" style="padding:10px;">


Note :- it take automatically base url (www.domain.com/media/). So you put only your image url.

No comments:

Post a Comment