You are here

public function GridStackForm::saveImage in GridStack 8

Saves the icon based on the current grid display.

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

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

File

modules/gridstack_ui/src/Form/GridStackForm.php, line 840

Class

GridStackForm
Extends base form for gridstack instance configuration form.

Namespace

Drupal\gridstack_ui\Form

Code

public function saveImage($data, &$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);
  file_unmanaged_save_data($file_contents, $uri, FILE_EXISTS_REPLACE);

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