Image Processing – Resize & Crop Category Images

categoryimage

I'd like to resize category images in my website, into square thumbnails. I have found and placed the following function in Mage/Catalog/Model/Category.php:

public function getResizedImage($width, $height = null, $quality = 100) {
    if (! $this->getImage ())
        return false;

    $imageUrl = Mage::getBaseDir ( 'media' ) . DS . "catalog" . DS . "category" . DS . $this->getImage ();
    if (! is_file ( $imageUrl ))
        return false;

    $imageResized = Mage::getBaseDir ( 'media' ) . DS . "catalog" . DS . "product" . DS . "cache" . DS . "cat_resized" . DS . $this->getImage ();// Because clean Image cache function works in this folder only
    if (! file_exists ( $imageResized ) && file_exists ( $imageUrl ) || file_exists($imageUrl) && filemtime($imageUrl) > filemtime($imageResized)) :
        $imageObj = new Varien_Image ( $imageUrl );
        $imageObj->constrainOnly ( true );
        $imageObj->keepAspectRatio ( true );
        $imageObj->keepFrame ( false );
        $imageObj->quality ( $quality );
        $imageObj->resize ( $width, $height );
        $imageObj->save ( $imageResized );
    endif;

    if(file_exists($imageResized)){
        return Mage::getBaseUrl ( 'media' ) ."/catalog/product/cache/cat_resized/" . $this->getImage ();
    }else{
        return $this->getImageUrl();
    }

}

and this is how it's used in template files:

<img src="<?php echo $category->getResizedImage(100,100); ?>" alt="<?php echo $category->getName(); ?>" />

But it's not working propely, images are not cropped and they're not resized into 100×100 pixels.

This function is suggested by many people having the same issue, but it's just not working for me. Any suggestions?

Best Answer

Check your code here,

$imageObj = new Varien_Image ( $imageUrl );
$imageObj=$imageObj->constrainOnly ( true )
->keepAspectRatio ( true )
->keepFrame ( false )
->quality ( $quality )
->resize ( $width, $height )
->save ( $imageResized );

This code will work.because you are not storing the return values of each code you used after this $imageObj = new Varien_Image ( $imageUrl ).

Related Topic