0

I'm trying to use the Imager-Craft plugin to make specific image transformations, but cannot figure out how to access Imager within the element-api.php file.

Imager shows plenty of template examples, but I'm not sure how to translate template code like this into straight Element API php.

{% set image = craft.assets().one() %}
{% set transformedImage = craft.imager.transformImage(image, { width: 1000 }) %}
<img src="{{ transformedImage.url }}">```

Specifically, I'm trying to access that craft.imager.transformImage function.

Is this possible?

  • I see people using craft()->plugins->getPlugin('Imager'), but this doesn't seem to work in Craft 3 with Element API v2. I there a v2 equivalent? – Scott Thiessen Oct 2 '18 at 18:41
3

In yii2 every instance of a module is stored in a public static property of the main class.

If the plugin is called image you can grab it via

Imager::getInstance()

This instance contains all the required components. The imager plugin it has 3 components

$this->setComponents([
    'imager' => ImagerService::class,
    'placeholder' => PlaceholderService::class,
    'color' => ImagerColorService::class,
]);

You can access those via Imager::getInstance()->imager or placeholder or color in this case the instance of the plugin is also stored in a static $plugin variable. You can call

Imager::$plugin->imager

as well. You can see a working example here

use aelvan\imager\Imager as Plugin;
.... 
return Plugin::$plugin->imager->isAnimated($asset);

This is the function that is being called when you do craft.imager.transform -> the PHP equivalent what you want to do

| improve this answer | |
0

I was able to find a working solution, but really not sure if this is the best way use a plugin in the Element API.

'transformer' => function(Entry $entry) {

    $imager = new aelvan\imager\services\ImagerService();
    $image  = $entry->image->one();

    $resizedImage = $imager->transformImage($image, [
        'width' => 100
    ]);

    return [
        'image' => $resizedImage->url
    ];
},
| 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.