View source
<?php
namespace Drupal\imagick\Plugin\ImageToolkit\Operation\imagick;
use Imagick;
use ImagickPixel;
class DefineCanvas extends ImagickOperationBase {
protected function arguments() {
return [
'HEX' => [
'description' => 'The color of the canvas',
],
'under' => [
'description' => 'This will create a solid flat layer, probably totally obscuring the source image',
],
'exact_measurements' => [
'description' => 'Do we have to use exact measurements',
],
'exact' => [
'description' => 'Exact measurements',
],
'relative' => [
'description' => 'Relative measurements',
],
];
}
protected function process(Imagick &$resource, array $arguments) {
$color = $arguments['HEX'];
$under = $arguments['under'];
$exact_size = $arguments['exact_measurements'];
$exact = $arguments['exact'];
$relative = $arguments['relative'];
$canvas = new Imagick();
$canvas
->setFormat($resource
->getImageFormat());
$color = empty($color) ? 'none' : $color;
if ($exact_size) {
$width = $this::imagick_percent_filter($exact['width'], $resource
->getImageWidth());
$height = $this::imagick_percent_filter($exact['height'], $resource
->getImageHeight());
list($x, $y) = explode('-', $exact['anchor']);
$x = image_filter_keyword($x, $width, $resource
->getImageWidth());
$y = image_filter_keyword($y, $height, $resource
->getImageHeight());
}
else {
$width = $resource
->getImageWidth() + $relative['leftdiff'] + $relative['rightdiff'];
$height = $resource
->getImageHeight() + $relative['topdiff'] + $relative['bottomdiff'];
$x = $relative['leftdiff'];
$y = $relative['topdiff'];
}
if (!$canvas
->newImage($width, $height, new ImagickPixel($color))) {
return FALSE;
}
if ($under && !$canvas
->compositeImage($resource, Imagick::COMPOSITE_DEFAULT, $x, $y)) {
return FALSE;
}
$resource = clone $canvas;
return TRUE;
}
private function imagick_percent_filter($length_specification, $current_length) {
if (strpos($length_specification, '%') !== FALSE) {
$length_specification = $current_length !== NULL ? str_replace('%', '', $length_specification) * 0.01 * $current_length : NULL;
}
return $length_specification;
}
}