You are here

public function GDToolkit::save in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php \Drupal\system\Plugin\ImageToolkit\GDToolkit::save()
  2. 9 core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php \Drupal\system\Plugin\ImageToolkit\GDToolkit::save()

File

core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php, line 220

Class

GDToolkit
Defines the GD2 toolkit for image manipulation within Drupal.

Namespace

Drupal\system\Plugin\ImageToolkit

Code

public function save($destination) {
  $scheme = StreamWrapperManager::getScheme($destination);

  // Work around lack of stream wrapper support in imagejpeg() and imagepng().
  if ($scheme && $this->streamWrapperManager
    ->isValidScheme($scheme)) {

    // If destination is not local, save image to temporary local file.
    $local_wrappers = $this->streamWrapperManager
      ->getWrappers(StreamWrapperInterface::LOCAL);
    if (!isset($local_wrappers[$scheme])) {
      $permanent_destination = $destination;
      $destination = $this->fileSystem
        ->tempnam('temporary://', 'gd_');
    }

    // Convert stream wrapper URI to normal path.
    $destination = $this->fileSystem
      ->realpath($destination);
  }
  $function = 'image' . image_type_to_extension($this
    ->getType(), FALSE);
  if (!function_exists($function)) {
    return FALSE;
  }
  if ($this
    ->getType() == IMAGETYPE_JPEG) {
    $success = $function($this
      ->getResource(), $destination, $this->configFactory
      ->get('system.image.gd')
      ->get('jpeg_quality'));
  }
  else {

    // Image types that support alpha need to be saved accordingly.
    if (in_array($this
      ->getType(), [
      IMAGETYPE_PNG,
      IMAGETYPE_WEBP,
    ], TRUE)) {
      imagealphablending($this
        ->getResource(), FALSE);
      imagesavealpha($this
        ->getResource(), TRUE);
    }
    $success = $function($this
      ->getResource(), $destination);
  }

  // Move temporary local file to remote destination.
  if (isset($permanent_destination) && $success) {
    try {
      $this->fileSystem
        ->move($destination, $permanent_destination, FileSystemInterface::EXISTS_REPLACE);
      return TRUE;
    } catch (FileException $e) {
      return FALSE;
    }
  }
  return $success;
}