Get and Resize Category Images

Posted About 11 years ago. Visible to the public.
public function getCategoryImage(Mage_Catalog_Model_Category $category, $width = 250, $height = 250)
{
    // return when no image exists
    if (!$category->getImage()) {
        return false;
    }

    // return when the original image doesn't exist
    $imagePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category'
               . DS . $category->getImage();
    if (!file_exists($imagePath)) {
        return false;
    }

    // resize the image if needed
    $rszImagePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category'
                  . DS . 'cache' . DS . $width . 'x' . $height . DS
                  . $category->getImage();
    if (!file_exists($rszImagePath)) {
        $image = new Varien_Image($imagePath);
        $image->resize($width, $height);
        $image->save($rszImagePath);
    }

    // return the image URL
    return Mage::getBaseUrl('media') . '/catalog/category/cache/' . $width . 'x'
         . $height . '/' . $category->getImage();
}

Note: Category object from getChildrenCategories() has a limited amount of data, you will need to load the entire object with:
$category->load($category->getId())

Michael O'Loughlin
Last edit
Over 10 years ago
Posted by Michael O'Loughlin to Magento (2013-01-30 16:45)