我正在为自定义类别视图中的每个图片检索网址:
像这样:
foreach ($collection as $cat){
$cur_category = Mage::getModel('catalog/category')->load($cat->getId());
$_img = $cur_category->getImageUrl();
//stuff
}
这是给我原始图像,我想使用Magento的内置调整大小功能调整大小。但我是一个新手,并且无法弄清楚如何使代码像产品列表页面上的代码一样工作:
$this->helper('catalog/image')->init($_product, 'small_image')->resize(306);
如何修改/使用原始代码以调整图像大小?谢谢!
答案 0 :(得分:17)
没有用于调整类别图像大小的内置功能。但是,您可以使用Varien_Image
课程。在这里,我写了一段你需要的代码:
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;
}
}
答案 1 :(得分:3)
您不应该使用Mage :: getBaseDir('media')直接调用图像输出到浏览器,否则您会邀请黑客篡改您的服务器。使用Mage :: getUrl('media')获取媒体目录的URL,如下所示:
foreach ($categories as $category) {
$category = Mage::getModel('catalog/category')->load($category->getId());
$category_name = $this->stripTags($category->getName(), null, true);
$category_url = $category->getUrl();
$category_img = $category->getImage();
$media_dir = Mage::getBaseDir('media').DS.'catalog'.DS.'category'.DS;
$cache_dir = $media_dir.'cache'.DS;
$cache_url = Mage::getUrl('media').'catalog'.DS.'category'.DS.'cache'.DS;
if (file_exists($cache_dir.$category_img)) {
$category_img_url = $cache_url.$category_img;
} elseif (file_exists($media_dir.$category_img)) {
if (!is_dir($cache_dir)) {
mkdir($cache_dir);
}
$image = new Varien_Image($media_dir.$category_img);
$image->constrainOnly(true);
$image->keepAspectRatio(true);
$image->keepFrame(true);
$image->keepTransparency(true);
$image->resize(140, 140);
$image->save($cache_dir.$category_img);
$category_img_url = $cache_url.$category_img;
}
}