han*_*ace 6 php gd image silverstripe
我希望能够在控制器中返回黑白图像,因此我可以在模板中使用它.在这个页面上,我发现GD类有一个灰度方法.不幸的是我不理解GD类以及如何使用它.我试过了
$final = $image->getFormattedImage('greyscale',36,36,36);
Run Code Online (Sandbox Code Playgroud)
但那没用.它确实返回带有新URL的图像对象,但图像不存在.
任何人都可以向我解释如何在Silverstripe页面控制器中将imageobject制作成灰度图像?
mun*_*ono 10
好吧,我自己去了,这就是我想出来的:
_config.php
Object::add_extension('Image', 'Greyscaled');
Run Code Online (Sandbox Code Playgroud)
更新:从SilverStripe 3.1开始,您应该使用配置系统而不是_config.php.将以下内容放入您的mysite/_config/config.yml(添加后不要忘记?flush=1重新加载配置缓存):
Image:
extensions:
- 'Greyscaled'
Run Code Online (Sandbox Code Playgroud)
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
UPDATE2: 3.1的更新版本?您可以传递2个以上的参数,GD已重命名为Image_Backend.这样,图像名称中的RGB值之间就没有空格.请注意$ gd-> greyscale需要很多果汁 - 所以你可能会先缩小尺寸,然后再使用GreyscaleImage.
更新3:由于这个答案最近获得了一些投票,我认为人们仍在使用它,但我认为在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);
}
}
Run Code Online (Sandbox Code Playgroud)
并在模板中:
<img src="$Images.GreyscaleImage.CroppedImage(1000,400).URL" alt="$Images.Title" />
Run Code Online (Sandbox Code Playgroud)