Creating grayscale images in Silverstripe

I would like to be able to return the image to Black & white in the controller, so I can use it in the template. On this page I found that the GD class has a grayscale method. Unfortunately, I do not understand the GD class and how to use it. I tried to do

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

But that did not work. It returns an image object with a new URL, but the image does not exist.

Can someone explain to me how to make an image object in a grayscale image on a Silverstripe Controller page?

+6
source share
2 answers

Well, I myself went, and this is what I came up with:

_config.php

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

UPDATE: as of SilverStripe 3.1, you should use the configuration system instead of _config.php . Put the mysite/_config/config.yml in mysite/_config/config.yml (do not forget ?flush=1 reload the configuration cache after adding):

 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: With newer versions 3.1? you can pass more than two parameters, and GD has been renamed Image_Backend. This way you have no spaces between the RGB values ​​in the image name. Be aware that $ gd-> greyscale needs a lot of juice, so you can reduce the size and GreyscaleImage first.

UPDATE3:. Since this answer received several votes, I assume that people are still using it, but I think that in 2017 CSS filters are in many cases the best choice. With the prefix, you will have about 90% coverage. 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); } } 

and in the template:

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

Silverstripe 3.1 Image API

+10
source

There is a module for this. Sorry, but not yet in the package. https://github.com/NightJar/ssrigging-greyscaleimages

0
source

Source: https://habr.com/ru/post/957500/


All Articles