You are here

protected function AddWatermark::execute in Basic Watermark 8

Performs the actual manipulation on the image.

Image toolkit operation implementers must implement this method. This method is responsible for actually performing the operation on the image. When this method gets called, the implementer may assume all arguments, also the optional ones, to be available, validated and corrected.

Parameters

array $arguments: An associative array of arguments to be used by the toolkit operation.

Return value

bool TRUE if the operation was performed successfully, FALSE otherwise.

Overrides ImageToolkitOperationBase::execute

File

src/Plugin/ImageToolkit/Operation/gd/AddWatermark.php, line 55

Class

AddWatermark
Defines GD2 Add Watermark operation.

Namespace

Drupal\basic_watermark\Plugin\ImageToolkit\Operation\gd

Code

protected function execute(array $arguments) {
  $image_resource = $this
    ->getToolkit()
    ->getResource();
  $watermark_filepath = DRUPAL_ROOT . $arguments['watermark_path'];
  $watermark_image = imagecreatefrompng($watermark_filepath);
  $image['width'] = imagesx($image_resource);
  $image['height'] = imagesy($image_resource);
  $watermark = $this
    ->scaleWatermark($watermark_image, $image, $arguments['margins']);
  $margins = $this
    ->getMargins($image, $watermark, $arguments['position'], $arguments['margins']);
  $temp_resource = $this
    ->getToolkit()
    ->getResource();
  switch ($arguments['apply_type']) {
    case 'repeat':

      // Repeat always starts from top left.
      $start_x = $arguments['margins']['left'];
      for ($i = 0; $i < $image['width'] / $watermark['width'] + 1; $i++) {
        $start_y = $arguments['margins']['top'];
        for ($j = 0; $j < $image['height'] / $watermark['height'] + 1; $j++) {
          $resource = imagecopy($temp_resource, $watermark['image'], $start_x, $start_y, 0, 0, min($watermark['width'], $image['width'] - $start_x), min($watermark['height'], $image['height'] - $start_y));

          // If at any point the image copy fails fail the operation.
          if (!$resource) {
            $this
              ->getToolkit()
              ->setResource($image_resource);
            return FALSE;
          }
          $start_y += $arguments['margins']['top'] + $watermark['height'];
        }
        $start_x += $arguments['margins']['left'] + $watermark['width'];
      }
      break;
    case 'once':
      $resource = imagecopy($temp_resource, $watermark['image'], $margins['x'], $margins['y'], 0, 0, $watermark['width'], $watermark['height']);
      if (!$resource) {
        $this
          ->getToolkit()
          ->setResource($image_resource);
        return FALSE;
      }
      break;
    default:
      return FALSE;
  }
  $this
    ->getToolkit()
    ->setResource(TRUE);
  imagedestroy($image_resource);
  return TRUE;
}