【问题标题】:Making Greyscale image in Silverstripe在 Silverstripe 中制作灰度图像
【发布时间】:2013-11-17 16:33:00
【问题描述】:

我希望能够在控制器中返回黑白图像,以便在模板中使用它。在this page我发现GD类有灰度方法。不幸的是,我不了解 GD 类以及如何使用它。我试过做

$final = $image->getFormattedImage('greyscale',36,36,36);

但这没有用。它确实返回了一个带有新 URL 的图像对象,但该图像不存在。

谁能向我解释如何在 Silverstripe 页面控制器中将图像对象制作成灰度图像?

【问题讨论】:

  • 是的,我发现不幸的是,这篇文章适用于 2.4,并且自 2.4 以来发生了很多变化。所以它对我不起作用

标签: php image gd silverstripe


【解决方案1】:

好吧,我自己尝试了一下,这就是我想出的:

_config.php

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

更新:从 SilverStripe 3.1 开始,您应该使用配置系统而不是 _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 ??您可以传入超过 2 个参数,并且 GD 已重命名为 Image_Backend。这样,图像名称中的 RGB 值之间就没有空格。请注意 $gd->greyscale 需要大量的汁液 - 所以您最好先缩小尺寸,然后再缩小 GreyscaleImage。

更新3:由于这个答案最近获得了一些投票,我认为人们仍在使用它,但我认为在 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

【讨论】:

    【解决方案2】:

    为此有一个模块。抱歉,它还没有出现在 packagist 上。 https://github.com/NightJar/ssrigging-greyscaleimages

    【讨论】:

    • True 但模块无法设置 RGB 值,也没有为通道使用合理的默认权重。输出看起来不像它应该的那样:(
    猜你喜欢
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2014-12-11
    • 2018-03-18
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    相关资源
    最近更新 更多