我希望能够在控制器中以黑白方式返回图像,因此可以在模板中使用它。在此页面上,我发现GD类具有灰度方法。不幸的是,我不理解GD类以及如何使用它。我试着做
$final = $image->getFormattedImage('greyscale',36,36,36);
但这没有用。它确实返回具有新URL的图像对象,但是该图像不存在。
谁能向我解释如何在Silverstripe页面控制器中将图像对象转换为灰度图像?
好吧,我自己去了,这就是我想出的:
_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需要大量汁液-因此您可能会先缩小尺寸,然后再缩小尺寸。
UPDATE3:因为这个答案最近获得了一些投票,所以我认为人们仍在使用它,但是我认为在2017年,CSS过滤器在许多情况下是一个更好的选择。加上前缀,您将拥有近90%的覆盖率。caniuse.com上的css-filters
<?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" />
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句