You are here

public static function Watermark::createImage in Media watermark 8

Function to create image (.jpg, .jpeg, .png, .gif) file.

Used in batch callback function and as before on file upload form.

Parameters

\Drupal\file\Entity\File $file: Drupal file object.

\Drupal\media_watermark\Entity\MediaWatermark $watermark: Watermark entity object.

string $type: Type of image operation.

1 call to Watermark::createImage()
Watermark::batchCreateImage in src/Watermark/Watermark.php
Batch worker function.

File

src/Watermark/Watermark.php, line 89

Class

Watermark
Custom watermark class.

Namespace

Drupal\media_watermark\Watermark

Code

public static function createImage($file, $watermark, $type = 'add') {

  // Get file real path.
  $file_path = \Drupal::service('file_system')
    ->realpath($file
    ->getFileUri());

  // Get watermark file id.
  $fid = $watermark
    ->getFid();
  if (!empty($fid) && is_array($fid)) {
    $fid = reset($fid);
  }
  else {

    // If none then do nothing.
    \Drupal::messenger()
      ->addStatus(t("Watermark doesn't have file to be applied."));
    return;
  }

  // Watermark file object.
  $watermark_file = File::load($fid);

  // Get watermark file real path to get image extension.
  $watermark_filepath = \Drupal::service('file_system')
    ->realpath($watermark_file
    ->getFileUri());
  $watermark_extension = pathinfo($watermark_filepath, PATHINFO_EXTENSION);

  // Check uploaded image extension.
  $ext = pathinfo($file_path, PATHINFO_EXTENSION);

  // We need to use appropriate functions when save image.
  $ext = self::getFuncName($ext);
  if (!empty($ext)) {
    $func_name = 'imagecreatefrom' . self::getFuncName($ext);
    $img = $func_name($file_path);

    // Check if not empty image file and extension then proceed with adding
    // watermark.
    if (!empty($img)) {

      // Get watermark image.
      $get_watermark = 'imagecreatefrom' . $watermark_extension;
      $watermark_img = $get_watermark($watermark_filepath);
      ob_start();
      $im = self::addWatermark($img, $watermark_img, $watermark, $ext);
      $func_name = self::getFuncName($ext);
      $func_name = 'image' . $func_name;
      $func_name($im, $file_path);
      imagedestroy($im);
      ob_end_clean();

      // We need to call this function to flush image cache only for updated
      // images.
      self::flushImageStylesCache($file
        ->getFileUri());
    }
  }
  else {
    \Drupal::messenger()
      ->addWarning(t('Unknown or unsupported image extension.'));
  }
}