Magento: Resize image Function

1
293
views
Advertisement

Hi, Everyone

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.

1. Put Below function on your module Block or helper file.Here in this function i have used 4 parameter ($image,$type,$width,$height).So, You have to set all the parameter where u call Below function.

Here is the custom image resize function. This function will resize image proportionally.

public function getImageresize($image,$type,$width,$height)
{
    //IMAGE RESIZE CODE START
if(!file_exists(Mage::getBaseDir(‘media’).’/artist/resized/’.$type.’/’))mkdir(Mage::getBaseDir(‘media’).’/artist/resized/’.$type.’/’,0777);
    $imageUrl = Mage::getBaseDir(‘media’).’/artist/’.$image;             
    if($imageUrl):
        $imageName = substr(strrchr($imageUrl,”/”),1);
        $imageResized = Mage::getBaseDir(‘media’).DS.”artist”.DS.”resized”.DS.””.$type.””.DS.$imageName;
        $dirImg = Mage::getBaseDir().str_replace(“/”,DS,strstr($imageUrl,’/media’));
        if (!file_exists($imageResized)&&file_exists($dirImg)) :
            $imageObj = new Varien_Image($imageUrl);
            $imageObj->constrainOnly(TRUE);
            $imageObj->keepAspectRatio(TRUE);
            $imageObj->keepFrame(TRUE);
            $imageObj->backgroundColor(array(255,255,255));
            //Uncomment below Code if u want to use.
            //$imageObj->backgroundColor(false);
            //$imageObj->keepTransparency(True);
            //$imageObj->setImageBackgroundColor(false);             
            //$imageObj->quality(100);
            //$imageObj->setWatermarkImageOpacity(0);
            $imageObj->resize($width, $height);
            $imageObj->save($imageResized);
        endif;
        return Mage::getBaseUrl(‘media’).”artist/resized/”.$type.”/”.$imageName;
    endif;
    //IMAGE RESIZE CODE END
}

2. Put the following code in template (.phtml) file to display the resized image:

<?php echo $this->getImageresize(imagepath,’thumb’,148,141);?>


Ok, we are done !!! Please leave your comments here. 🙂

I hope this helps someone 🙂

Thanx,
Mayank Zalavadia  🙂