You are here

private function AddWatermark::scaleWatermark in Basic Watermark 8

Scales the watermark to fit in the image.

The watermark will only be scaled down if its too big, taking into consideration the provided margins.

Parameters

resource $watermark_image: The watermark gd resource.

array $image: An array with the width and height of the image to apply the watermark.

array $margins: The margins to keep around the watermark.

Return value

array An array of the scaled watermark as well as its width and height.

1 call to AddWatermark::scaleWatermark()
AddWatermark::execute in src/Plugin/ImageToolkit/Operation/gd/AddWatermark.php
Performs the actual manipulation on the image.

File

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

Class

AddWatermark
Defines GD2 Add Watermark operation.

Namespace

Drupal\basic_watermark\Plugin\ImageToolkit\Operation\gd

Code

private function scaleWatermark($watermark_image, array $image, array &$margins) {
  $watermark['width'] = imagesx($watermark_image);
  $watermark['height'] = imagesy($watermark_image);

  // If the width of the margins exceed the image height remove the margins.
  if ($margins['left'] + $margins['right'] >= $image['width']) {
    $margins['left'] = 0;
    $margins['right'] = 0;
  }

  // If the height of the margins exceed the image height remove the margins.
  if ($margins['top'] + $margins['bottom'] >= $image['height']) {
    $margins['top'] = 0;
    $margins['bottom'] = 0;
  }

  // Scale Watermark to fit on image horizontaly.
  if ($watermark['width'] + $margins['left'] + $margins['right'] > $image['width']) {
    $watermark['width'] = $image['width'] - $margins['left'] - $margins['right'];
    $watermark_image = imagescale($watermark_image, $watermark['width']);
    $watermark['height'] = imagesy($watermark_image);
  }

  // Scale Watermark to fit on image vertically.
  if ($watermark['height'] + $margins['top'] + $margins['bottom'] > $image['height']) {
    $watermark['height'] = $image['height'] - $margins['top'] - $margins['bottom'];

    // New width = new height * (original width / original height)
    $watermark['width'] = $watermark['height'] * (imagesx($watermark_image) / imagesy($watermark_image));
    $watermark_image = imagescale($watermark_image, $watermark['width'], $watermark['height']);
  }
  return [
    'image' => $watermark_image,
    'width' => $watermark['width'],
    'height' => $watermark['height'],
  ];
}