You are here

public function Random::image in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::image()

Create a placeholder image.

Parameters

string $destination: The absolute file path where the image should be stored.

string $min_resolution: The minimum resolution for the image. For example, '400x300'.

string $max_resolution: The maximum resolution for the image. For example, '800x600'.

Return value

string Path to image file.

File

core/lib/Drupal/Component/Utility/Random.php, line 276

Class

Random
Defines a utility class for creating random data.

Namespace

Drupal\Component\Utility

Code

public function image($destination, $min_resolution, $max_resolution) {
  $extension = pathinfo($destination, PATHINFO_EXTENSION);
  $min = explode('x', $min_resolution);
  $max = explode('x', $max_resolution);
  $width = rand((int) $min[0], (int) $max[0]);
  $height = rand((int) $min[1], (int) $max[1]);

  // Make an image split into 4 sections with random colors.
  $im = imagecreate($width, $height);
  for ($n = 0; $n < 4; $n++) {
    $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
    $x = $width / 2 * ($n % 2);
    $y = $height / 2 * (int) ($n >= 2);
    imagefilledrectangle($im, $x, $y, $x + $width / 2, $y + $height / 2, $color);
  }

  // Make a perfect circle in the image middle.
  $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
  $smaller_dimension = min($width, $height);
  imageellipse($im, $width / 2, $height / 2, $smaller_dimension, $smaller_dimension, $color);
  $save_function = 'image' . ($extension == 'jpg' ? 'jpeg' : $extension);
  $save_function($im, $destination);
  return $destination;
}