我希望能够在 Controller 中返回黑白图像,因此可以在模板中使用它。在this page上,我发现GD类具有灰度方法。不幸的是,我不理解GD类以及如何使用它。我试着做

$final = $image->getFormattedImage('greyscale',36,36,36);
但这是行不通的。它的确返回带有新URL的图像对象,但该图像不存在。
谁能向我解释如何在Silverstripe页面 Controller 中将图像对象转换为灰度图像?

最佳答案

好吧,我自己去了,这就是我想出的:

_config.php

Object::add_extension('Image', 'Greyscaled');

更新:从SilverStripe 3.1开始,应该使用config系统而不是_config.php。将以下内容放入mysite/_config/config.yml中(添加后请不要忘记使用?flush=1重新加载配置缓存):
Image:
  extensions:
    - 'Greyscaled'

Greyscaled.php

<?php
class Greyscaled extends DataExtension {
    //This allows the template to pick up "GreyscaleImage" property, it requests a copy of the image from the cache or if it doesn't exist, generates a new one
    public function GreyscaleImage($RGB = '76 147 29') {
        return $this->owner->getFormattedImage('GreyscaleImage', $RGB);
    }

    //This is called internally by "generateFormattedImage" when the item is not already cached
    public function generateGreyscaleImage(GD $gd, $RGB) {
        $Vars = explode(' ', $RGB);
        return $gd->greyscale($Vars[0], $Vars[1], $Vars[2]);
    }
}

UPDATE2:,带有3.1的较新版本?您可以传入两个以上的参数,并且GD已重命名为Image_Backend。这样,在图像名称中的RGB值之间就没有空格。请注意,$ gd-> greyscale需要大量的汁液-因此您最好先减小尺寸,然后再减小GreyscaleImage。

UPDATE3:由于这个答案最近获得了一些投票,我认为人们仍然在使用它,但是我认为在2017年CSS过滤器在许多情况下是一个更好的选择。前缀您将拥有接近90%的覆盖率。
css-filters on caniuse.com

<?php
class Greyscaled extends DataExtension {
    public function GreyscaleImage($R = '76', $G = '147', $B = '29') {
        return $this->owner->getFormattedImage('GreyscaleImage', $R, $G, $B);
    }
    public function generateGreyscaleImage(Image_Backend $gd, $R, $G, $B) {
        return $gd->greyscale($R, $G, $B);
    }
}

并在模板中:

<img src="$Images.GreyscaleImage.CroppedImage(1000,400).URL" alt="$Images.Title" />

Silverstripe 3.1 Image API

关于php - 在Silverstripe中制作灰度图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19812073/

10-12 12:38
查看更多