You are here

public static function Utilities::createImage in Formatter Suite 8

Returns a data URL for an image of the given color and size.

Parameters

string $color: A CSS-style hex color (e.g. #ff00ff).

int $width: (optional, default = 1 pixel) The image width.

int $height: (optional, default = 1 pixel) The image height.

Return value

string Returns a data URL string containing a PNG image using the given color.

1 call to Utilities::createImage()
GeneralNumberWithBarIndicatorFormatter::viewElements in src/Plugin/Field/FieldFormatter/GeneralNumberWithBarIndicatorFormatter.php
Builds a renderable array for a field value.

File

src/Utilities.php, line 37

Class

Utilities
Defines utility functions used throughout the module.

Namespace

Drupal\formatter_suite

Code

public static function createImage(string $color, int $width = 1, int $height = 1) {

  // Parse color.
  if (strlen($color) === 4) {
    list($r, $g, $b) = sscanf($color, "#%1x%1x%1x");
    $r *= 16;
    $g *= 16;
    $b *= 16;
  }
  else {
    list($r, $g, $b) = sscanf($color, "#%2x%2x%2x");
  }

  // Create an image and set its color to the given color.
  $image = @imagecreatetruecolor($width, $height);
  $background = @imagecolorallocate($image, $r, $g, $b);
  imagefilledrectangle($image, 0, 0, $width, $height, $background);

  // Output the image into a binary string.
  ob_start();
  imagepng($image, NULL, 0);
  $data = ob_get_contents();
  ob_end_clean();

  // Convert the binary image string to a base 64 PNG data URL.
  return 'data:image/png;base64,' . base64_encode($data);
}