Magento裁剪图片?

dat*_*.io 1 image crop magento

我发现了这个:http://docs.magentocommerce.com/Varien/Varien_Image/Varien_Image.html#crop

但我不确定这是否已被弃用或因为我试过这个时:

echo rawurlencode($this->helper('catalog/image')->init($_product, 'image')->constrainOnly(TRUE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->setWatermarkImageOpacity(0)->crop(10, 20, 30, 40)->resize(300, null))
Run Code Online (Sandbox Code Playgroud)

它不起作用,并给我这个错误:

Fatal error:  Call to undefined method Mage_Catalog_Helper_Image::crop() in /home/xxxxx/public_html/app/design/frontend/default/xxxxx/template/catalog/product/view.phtml
Run Code Online (Sandbox Code Playgroud)

那么crop()方法实际上是否可用?如果是的话,我如何使用它来裁剪(不要与调整大小混淆)Magento的产品图片?谢谢!

Vin*_*nai 5

你的错误是假设$this->helper('catalog/image')->init($_product, 'image')返回一个Varien_Image实例,实际上涉及两个中间类:
Mage_Catalog_Helper_ImageMage_Catalog_Model_Product_Image.

catalog/image助手是一个烂摊子,即使它已经在最近版本的被清理了一下(例如,没有更多的私有方法).尽管如此,一些吸气剂在没有真正需要的情况下仍然受到保护.
这是我的解决方法:

/* @var $imageHelper Mage_Catalog_Helper_Image */
// Initialize the image helper
$imageHelper = Mage::helper('catalog/image')->init($_product, 'image')
        ->constrainOnly(true)
        ->keepAspectRatio(true)
        ->keepFrame(false)
        ->setWatermarkImageOpacity(0);

// Get the catalog/product_image instance
/* @var $imageModel Mage_Catalog_Model_Product_Image */
$reflection = new ReflectionClass($imageHelper);
$property = $reflection->getProperty('_model');
$property->setAccessible(true);
$imageModel = $property->getValue($imageHelper);

// Initialize the missing values on the image model
// Usually done in Mage_Catalog_Helper_Image::__toString()
if (! $imageModel->isCached())
{
    $getWatermarkMethod = $reflection->getMethod('getWatermark');
    $getWatermarkMethod->setAccessible(true);
    $imageModel->setBaseFile($_product->getImage())
        ->resize()
        ->setWatermark($getWatermarkMethod->invoke($imageHelper));

    // Crop the image using the image processor
    // $imageModel->getImageProcessor() returns a Varien_Image instance
    $imageModel->getImageProcessor()->crop(10, 20, 30, 40);

    // Generate the image according to the set parameters and
    // get the URL while bypassing the helper to avoid reinitialization
    $url = $imageModel->saveFile()->getUrl();
}
echo $url . "\n";
Run Code Online (Sandbox Code Playgroud)

使用该catalog/product_image模型或Varien_Image直接使用该模型会更容易,但这样仍然可以应用所有Magento水印设置.
无论哪种方式都不干净.
我希望助手的助手在未来的版本中公之于众.