Magento: Get resized catalog thumbnail image

My solution for generating a resized thumbnail image is to overwrite the  model class of catalog. Here my xml file:

<?xml version="1.0"?>
<config>
  <global>
    <models>
      <catalog>
        <rewrite>
           <category>YOURMODULE_SUBMODULE_Model_Catalog_Category</category>
        </rewrite>
      </catalog>
    </models>
  </global>
</config>

The class (/app/code/local/YOURMODULE/SUBMODULE/Model/Catalog/Category.php):

class YOURMODULE_SUBMODULE_Model_Catalog_Category extends Mage_Catalog_Model_Category
{
  public function getResizedThumbnail($width = 130, $height = 130) {

    if (! $this->getThumbnail()) return false;

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

    $imageResized = Mage::getBaseDir ( 'media' ) .DS . "catalog" . DS . "category" . DS . "cache" . DS . "cat_resized" . DS . $this->getThumbnail();

    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" . DS . "category" . DS . "cache" . DS . "cat_resized" . DS . $this->getThumbnail();
    }else{
      return $this->getThumbnail();
    }
  }
}

Now you can call the the method $category->getResizedThumbnail() in your view.phtml

Sven Wappler

TYPO3 Experte, symfony, Magento, SEO, Frontend und Backend

Das könnte Dich auch interessieren …

3 Antworten

  1. Stefan Maier sagt:

    Thanks for this great little Extension!

  2. q23.rst sagt:

    great, thanks.

    better enhance function with this
    $imageObj -> keepTransparency(true);
    to improve output

Schreibe einen Kommentar