Image toolkits

The Drupal 8 Image toolkits provide an abstraction layer over the most common operations used for manipulating images. By default, Drupal uses the GD image management library that is included with PHP. However, it also offers the ability to switch to a different library if needed by using the ImageToolkit plugins:

For instance, a contributed module could implement the ImageMagick library for developers who need support for additional image types such as TIFF, which GD does not support. However, only one library can be used at a time as it needs to be configured site-wide.

Programmatically manipulating images using a toolkit involves instantiating an ImageInterface object that wraps an image file. This interface (implemented by the Image class) contains all the needed methods for applying the common manipulations to images, as well as saving the resulting image to the filesystem. And to get our hands on such an object, we use the ImageFactory service:

$factory = Drupal::service('image.factory');  

The role of this factory is to create instances of Image using a given toolkit. And it works like this:

$image = $factory->get($uri);  

The second parameter to this method is the ImageToolkit plugin ID we want the Image object to work with. By default, it uses the default toolkit configured for the entire application.

And now we can use the manipulation methods on the ImageInterface to change the file:

$image->scale(50, 50); 
$image->save('public://thumbnail.jpg');  

In this example, we scale the image to 50 x 50 and save it to a new path. Omitting the destination in the save() method would mean overwriting the original file with the changed version. If you need to perform such manipulations manually, I encourage you to explore the ImageInterface for all the available options.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset