You are here

protected function GridStackFormBase::saveImage in GridStack 8.2

Saves the icon based on the current grid display.

Taken and simplified from color.module _color_render_images(), and s.o.

1 call to GridStackFormBase::saveImage()
GridStackFormBase::validateForm in modules/gridstack_ui/src/Form/GridStackFormBase.php
Form validation handler.

File

modules/gridstack_ui/src/Form/GridStackFormBase.php, line 975

Class

GridStackFormBase
Extends base form for gridstack instance configuration form.

Namespace

Drupal\gridstack_ui\Form

Code

protected function saveImage($data, array &$paths) {
  if (empty($data) || strpos($data, ',') === FALSE) {
    return;
  }
  $name = $paths['id'] . '.png';
  $uri = $paths['target'] . $name;
  $url = file_create_url($uri);
  $real_path = $this->fileSystem
    ->realpath($uri);

  // Remove "data:image/png;base64," part.
  $file_data = substr($data, strpos($data, ',') + 1);
  $file_contents = base64_decode($file_data);
  if (empty($file_contents)) {
    return;
  }
  $image = imagecreatefromstring($file_contents);

  // Gets dimensions.
  $width = imagesx($image);
  $height = imagesy($image);

  // Prepare target buffer.
  $target = imagecreatetruecolor($width, $height);
  $white = imagecolorallocate($target, 255, 255, 255);
  imagefilledrectangle($target, 0, 0, $width, $height, $white);
  imagecopy($target, $image, 0, 0, 0, 0, $width, $height);
  imagealphablending($target, TRUE);
  imagepng($target, $real_path);

  // Clean up target buffer.
  imagedestroy($target);

  // Store image.
  $paths['uri'] = $uri;
  $paths['url'] = file_url_transform_relative($url);
  $this->fileSystem
    ->saveData($file_contents, $uri, FileSystemInterface::EXISTS_REPLACE);

  // Set standard file permissions for webserver-generated files.
  $this->fileSystem
    ->chmod($real_path);
}