Magento:自定义功能可按比例调整图像大小

在我以前的文章中,使用Magento调整图像大小,我编写了直接代码来调整任何图像的大小。在这里,我将编写一个简单的函数来按比例调整图像大小,该函数可以保存在模块的帮助文件中(因为可以通过任何模板(.phtml)文件访问该帮助文件)。

这是自定义图像调整大小功能。此功能将按比例调整图像大小。

/**
 * Resize Image proportionally and return the resized image url 
 *
 * @param string $imageName            name of the image file
 * @param integer|null $width         resize width
 * @param integer|null $height         resize height
 * @param string|null $imagePath     directory path of the image present inside media directory
 * @return string                 full url path of the image
 */
public function resizeImage($imageName, $width=NULL, $height=NULL, $imagePath=NULL)
{        
    $imagePath = str_replace("/", DS, $imagePath);
    $imagePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $imageName;
    
    if($width == NULL && $height == NULL) {
        $width = 100;
        $height = 100; 
    }
    $resizePath = $width . 'x' . $height;
    $resizePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $resizePath . DS . $imageName;
            
    if (file_exists($imagePathFull) && !file_exists($resizePathFull)) {
        $imageObj = new Varien_Image($imagePathFull);
        $imageObj->constrainOnly(TRUE);
        $imageObj->keepAspectRatio(TRUE);
        $imageObj->resize($width,$height);
        $imageObj->save($resizePathFull);
    }
            
    $imagePath=str_replace(DS, "/", $imagePath);
    return Mage::getBaseUrl("media") . $imagePath . "/" . $resizePath . "/" . $imageName;
}

您可以在模板(.phtml)文件中编写以下代码,以显示调整后的图像:

<img src="<?php echo Mage::helper('moduleName')->resizeImage('abc.jpg', 400, 300, 'xyz/image'); ?>" alt="resized image" />

这里,

$ imageName是图像的名称(例如abc.jpg)

$ width是图像调整大小的宽度(例如400)
$ height是图像调整大小的高度(例如300)
(400类似于400px,300类似于300px)

$ imagePath是存储/保存图像的路径。该目录必须位于“ media”目录中。就像,如果我们将' xyz / image ' 指定为$ imagePath,那么我们的图像路径必须为' media / xyz / image / abc.jpg '($ imageName为abc.jpg)

我们将宽度和高度分别定义为400和300。因此,将创建一个名为“ 400×300”的新文件夹。新尺寸的图像将保存在这里。

如果width为null且height为300,则图像将以300px的固定高度按比例调整大小。文件夹名称将为“ x300”。

如果width为400而height为null,则图像将以400px的固定宽度按比例调整大小。文件夹名称将为“ 400x”。

如果width和height都不为null,则将图像调整为高度'100'和宽度'100'。文件夹名称将为“ 100×100”。

希望这可以帮助。谢谢。

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论