Magento 怎样 resize 网站的任意图片

2016年5月11日 浏览量 22 2 min read
Magento 怎样 resize 网站的任意图片

在magento实际应用中,我们经常会遇到,图片尺寸大小不合适的情况,比如我们要在用户中心添加一个广告图,但是图片尺寸需要resize一下,这时候又用不了magento自带的产品图片resize功能,所以在这里,我们来看一下如何给magento添加自定义的图片resize功能。

Magento之所以能够自如运营resize方法,追根到底,是因为加载了Varien_Image这个类,这个类在“lib/Varien/Image.php”,首先我们来看一下,magento进行图片resize的核心代码。


/**
* @return Varien_Image
*/
public function getImageProcessor()
{
if( !$this->_processor ) {
// var_dump($this->_checkMemory());
// if (!$this->_checkMemory()) {
// $this->_baseFile = null;
// }
$this->_processor = new Varien_Image($this->getBaseFile());
}
$this->_processor->keepAspectRatio($this->_keepAspectRatio);
$this->_processor->keepFrame($this->_keepFrame);
$this->_processor->keepTransparency($this->_keepTransparency);
$this->_processor->constrainOnly($this->_constrainOnly);
$this->_processor->backgroundColor($this->_backgroundColor);
$this->_processor->quality($this->_quality);
return $this->_processor;
}

最终实现逻辑的代码还是在varien_image中,所以,我们接下来要做的功能,就是来处理请求以及通过实例化varien_image来实现图片的resize功能。

首先建议加一个helper,这样我们就可以实现,写一次,用多次的目的了。


Mage::helper('resize')->resize($_imgUrl,100,100);

如下这是我们的一个helper,接下来再来看下这个方法所在的类以及方法的声明


<?php

class Magease_Resize_Helper_Data extends Mage_Core_Helper_Abstract {

/**
* Resize an image
*
* @param string $file
* @param int $width
* @param int $height
* @access public
* @return void
*/
public function resize($file, $width, $height = NULL) {

if (isset($file) && !empty($file)) {
$fileName = substr(strrchr($file, '/'), 1);
$filePath = str_replace(Mage::getBaseUrl(), '', $file);
}
$baseFile = Mage::getBaseDir() . DS . $filePath;

$basePath = Mage::getBaseDir() . DS . $filePath;
$newFile = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . "custom" . DS . "resized" . DS . $filePath;
if ($width != '') {
if (file_exists($baseFile) && is_file($baseFile) && !file_exists($newFile)) {
Mage::log('kaishi resize',null,'magease.log');
$imageObj = new Varien_Image($basePath);
$imageObj->constrainOnly(TRUE);
$imageObj->keepAspectRatio(FALSE);
$imageObj->keepFrame(FALSE);
$imageObj->resize($width, $height);
$imageObj->save($newFile);
}
$resizedURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . "custom" . DS . "resized" . DS . $filePath;
} else {
$resizedURL = $file;
}
return $resizedURL;
}

}

?>

通过如上代码,我们可以看到,实际上我们是通过实例化Varien_Image,通过向方法传递图片路径,宽和高三个参数,经过处理来实现图片的resize功能的。

Previous article:
Next article:
Comments
发表评论,留下你的足迹
我们不会公开你的邮箱地址

是否允许我们在发布新内容或者进行促销活动向您发送消息?

Remind me later

Thank you! Please check your email inbox to confirm.

Oops! Notifications are disabled.

© 2014-2023 www.magease.com. All Rights Reserved. 寰云网络 版权所有    鲁ICP备 14014975号-1