nortmas
11/20/2019 - 3:20 PM

SVG to PNG

/**
 * Convert SVG image to PNG.
 */
function beg_preprocess_svg_to_png($path, $dir = 'svg_to_png') {
  /** @var \Drupal\Core\File\FileSystem $file_system */
  $file_system = \Drupal::service('file_system');

  $basename = $file_system->basename($path);
  $file_name = explode('.', $basename)[0] . '.png';
  $dest_dir = 'sites/default/files/' . $dir;
  $dest = $dest_dir . '/' . $file_name;

  if ($path[0] === '/') {
    $path = substr($path, 1);
  }

  if ($file_system->prepareDirectory($dest_dir, $file_system::CREATE_DIRECTORY)) {
    if (file_exists($dest) === FALSE) {
      $svg = file_get_contents($path);
      $im = new Imagick();
      $im->readImageBlob($svg);
      $im->scaleImage(215, 70, TRUE);
      $im->setImageFormat("png24");
      $im->writeImage($dest);
      $im->clear();
      $im->destroy();

      $file = File::create([
        'uid' => 1,
        'filename' => $file_name,
        'uri' => 'public://' . $dir . '/' . $file_name,
        'status' => 1,
      ]);
      $file->save();

      return $dest;
    }
    else {
      return $dest;
    }
  }
  return NULL;
}