Randy Hall Randy Hall - 17 days ago 9
PHP Question

Resize image from URL in Magento

I am retrieving a url for each image in a custom category view:

Like so:

foreach ($collection as $cat){
$cur_category = Mage::getModel('catalog/category')->load($cat->getId());
$_img = $cur_category->getImageUrl();
//stuff
}


This is giving me the original image, I would like to resize using Magento's built in resize function. But I'm a newb, and can't figure out how to get that code to work like the code on the product list page:

$this->helper('catalog/image')->init($_product, 'small_image')->resize(306);


How do I modify/use the original code to make it resize the images? Thanks!

Answer

There is no built in functionality for resizing category images. However you can utilize Varien_Image class. Here I wrote a piece of code you need:

foreach ($collection as $_category){
    $_file_name = $_category->getImage();
    $_media_dir = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS;
    $cache_dir = $_media_dir . 'cache' . DS;
    if (file_exists($cache_dir . $_file_name)) {
        echo Mage::getBaseUrl('media') . DS . 'catalog' . DS . 'category' . DS . 'cache' . DS . $_file_name;
    } elseif (file_exists($_media_dir . $_file_name)) {
        if (!is_dir($cache_dir)) {
            mkdir($cache_dir);
        }

        $_image = new Varien_Image($_media_dir . $_file_name);
        $_image->constrainOnly(true);
        $_image->keepAspectRatio(true);
        $_image->keepFrame(true);
        $_image->keepTransparency(true);
        $_image->resize(50, 50);
        $_image->save($cache_dir . $_file_name);

        echo Mage::getBaseUrl('media') . DS . 'catalog' . DS . 'category' . DS . 'cache' . DS . $_file_name;
    }
}
Comments