I'd like to use the Image API directly to perform few simple operations with images (I'm aware of image styles and for various reasons I would prefer to not use image styles for the application I'm working on). The trouble I'm having is what I need to pass to the Image class as the first parameter. The constructor of the Image class expects an ImageToolkitInterface $toolkit as the first parameter. I'm not sure what to plug in for it.

Hunting around the forums, I see people have used \Drupal::service('image.toolkit') to pass in as the first parameter however this isn't working for me.

Here is a snippet of one of the operations I'm attempting to perform. Feel free to pan my whole approach.

use Drupal\Core\Controller\ControllerBase;    
use Drupal\Core\Image\Image;

class myImageController extends ControllerBase { 

  public function imageHeight() {

    $image_path = 'public://path/to/image.jpg';

    $image = new Image(\Drupal::service('image.toolkit'), $image_path);

    $image_height = $image->getHeight();


    return [

      '#markup' => $this->t('Did this work?'),

Does anyone know what I should use to pass in as the first parameter? I'm only using the default GD2 Image toolkit. Also, I'm on Drupal 8.6. Thanks!

  • $image = \Drupal::service('image.factory')->get($image_path);? – cchen Apr 7 '19 at 5:11
  • I like cchen's thinking. But, if you want to keep going with your current course, I'm not seeing an image.toolkit service, but I'm seeing an image.toolkit.manager service (api.drupal.org/api/drupal/core%21core.services.yml/service/…) - maybe that's what you want, or can use – Jaypan Apr 7 '19 at 6:49
  • Thanks cchen, your suggestion did the trick. Also, I tried the image.toolkit.manager but unfortunately that didn't work, thanks though for the suggestion. – mrlexington Apr 8 '19 at 1:06
$image = \Drupal::service('image.factory')->get($image_path); 

See the whole usage

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.