You are here

public function Webp::createWebpCopy in WebP 8

Creates a WebP copy of a source image URI.

Parameters

string $uri: Image URI.

int $quality: Image quality factor (optional).

Return value

bool|string The location of the WebP image if successful, FALSE if not successful.

File

src/Webp.php, line 84

Class

Webp
Class Webp.

Namespace

Drupal\webp

Code

public function createWebpCopy($uri, $quality = NULL) {
  $webp = FALSE;
  $toolkit = \Drupal::config('system.image')
    ->get('toolkit', FALSE);

  // Fall back to GD if the installed imagemagick does not support WEBP.
  if (!extension_loaded('imagick')) {
    $toolkit = 'gd';
  }
  elseif ($toolkit == 'imagemagick' && !in_array('WEBP', Imagick::queryFormats())) {
    $toolkit = 'gd';
  }
  if (is_null($quality)) {
    $quality = $this->defaultQuality;
  }
  if ($toolkit == 'imagemagick') {
    $webp = $this
      ->createImageMagickImage($uri, $quality);
  }
  else {

    // We assume $toolkit == 'gd'.
    // Generate a GD resource from the source image. You can't pass GD resources
    // created by the $imageFactory as a parameter to another function, so we
    // have to do everything in one function.
    $sourceImage = $this->imageFactory
      ->get($uri, 'gd');

    /** @var \Drupal\system\Plugin\ImageToolkit\GDToolkit $toolkit */
    $toolkit = $sourceImage
      ->getToolkit();
    $mimeType = $sourceImage
      ->getMimeType();
    $sourceImage = $toolkit
      ->getResource();

    // If we can generate a GD resource from the source image, generate the URI
    // of the WebP copy and try to create it.
    if ($sourceImage !== NULL) {
      $pathInfo = pathinfo($uri);
      $destination = strtr('@directory/@filename.webp', [
        '@directory' => $pathInfo['dirname'],
        '@filename' => $pathInfo['filename'],
        '@extension' => $pathInfo['extension'],
      ]);
      imagesavealpha($sourceImage, TRUE);
      imagealphablending($sourceImage, TRUE);
      imagesavealpha($sourceImage, TRUE);
      if (@imagewebp($sourceImage, $destination, $quality)) {

        // In some cases, libgd generates broken images. See
        // https://stackoverflow.com/questions/30078090/imagewebp-php-creates-corrupted-webp-files
        // for more information.
        if (filesize($destination) % 2 == 1) {
          file_put_contents($destination, "\0", FILE_APPEND);
        }
        @imagedestroy($sourceImage);
        $webp = $destination;
      }
      else {
        $error = $this
          ->t('Could not generate WebP image.');
        $this->logger
          ->error($error);
      }
    }
    else {
      $error = $this
        ->t('Could not generate image resource from URI @uri.', [
        '@uri' => $uri,
      ]);
      $this->logger
        ->error($error);
    }
  }
  return $webp;
}