# Using Imager X in PHP
Sometimes you may want to tap into Imager from your own plugin, module, or some other piece of PHP. This is as easy as using Craft itself, plugins like Imager is built using the same architecture. The key starting point is:
$imagerx = Craft::$app->plugins->getPlugin('imager-x');
Using Craft's plugins service, you can get a reference to the plugin itself. If Imager
doesn't exist or isn't installed, it'll return null
, so make sure you code defensively
and check for this:
$imagerx = Craft::$app->plugins->getPlugin('imager-x');
if ($imagerx && $imagerx instanceof \spacecatninja\imagerx\ImagerX) {
// do your thing
}
TIP
Although the $imagerx instanceof \spacecatninja\imagerx\ImagerX
conditional isn't
strictly necessary, it provides some extra security, and the added bonus is that you'll
get proper code hinting if you use an IDE like PhpStorm.
Through the plugin reference, you can get to the services that Imager itself uses:
// Transform an asset through the main `imager` service
$transforms = $imagerx->imager->transformImage($asset, 'myNamedTransform');
// Same, but setting the transform properties inline
$transforms = $imagerx->imager->transformImage($asset,
[
['width' => 800],
['width' => 1800]
],
[
'ratio' => 16/9
],
[
'fillTransforms' => true
]);
// Get the srcset based on a set of transformed images
$srcset = $imagerx->imager->srcset($transforms);
// Get the dominant color from an image through the `color` service
$dominantColor = $imagerx->color->getDominantColor($asset, 10, 'hex');
// Get a placeholder through the `placeholder` service
$placeholder = $imagerx->placeholder->placeholder([ 'color' => $dominantColor ]);
TIP
The service methods are currently not documented, so the best way to get an
overview of what is possible, is to dive into the services themselves (in
/src/services
in the repository), or use code hinting to see what's available.
A typical usecase for accessing Imager's service methods directly, is when using the Element API. This example builds on the example from the Element API docs, and adds a srcset to each news item in a news list json:
<?php
use craft\elements\Entry;
use craft\helpers\UrlHelper;
return [
'endpoints' => [
'news.json' => function() {
return [
'elementType' => Entry::class,
'criteria' => ['section' => 'news'],
'transformer' => function (Entry $entry) {
$imagerx = Craft::$app->plugins->getPlugin('imager-x');
$thumbSrcset = '';
if ($imagerx && $imagerx instanceof \spacecatninja\imagerx\ImagerX) {
$heroImage = $entry->image->one();
$transforms = $imagerx->imager->transformImage($heroImage, 'listThumbnail');
$thumbSrcset = $imagerx->imager->srcset($transforms);
}
return [
'title' => $entry->title,
'url' => $entry->url,
'jsonUrl' => UrlHelper::url("news/{$entry->id}.json"),
'summary' => $entry->summary,
'thumbSrcset' => $thumbSrcset,
];
},
];
},
]
];