Source Code for /public/appendix-samples/random-image-with-effect.php

<?php
// Get a list of all the .jpg files in the img/fruit directory:
$jpgs = glob('../img/fruit/*.jpg');
// Get a list of all the .webp files in the img/fruit directory:
$webps = glob('../img/fruit/*.webp');

// Combine both arrays into one:
$files = array_merge( $jpgs, $webps );

// Select a random file:
$random_file_id = array_rand($files);
$random_file = $files[ $random_file_id ];

// A list of CSS effects to apply to the image:
$effects = [
  'filter: grayscale(100%)',
  'filter: blur(2px)',
  'filter: brightness(1.5)',
  'filter: contrast(1.5)',
  'filter: hue-rotate(90deg)',
  'filter: invert(1)',
  'filter: sepia(1)',
  'transform: rotateZ(90deg);',
  'transform: skewX(-15deg);',
];

// Select a random effect:
$random_effect_id = array_rand($effects);
$random_effect = $effects[ $random_effect_id ];

// Tip: if you wanted to apply multiple different effects, you could use:
// - `shuffle($effects)` to put the list of effects into a random order, then
// - `$random_effects = array_slice($effects, 0, 2);` to choose the first two effects from the shuffled list, then
// - `$style = implode(';', $random_effects);` to join the effects into a single string, separating them by semicolons
// You could then `echo $style;` within the style="..." attribute to apply the effects!

?>
<p>
  <img src="<?php echo $random_file; ?>"
      width="200"
      height="200"
      style="border: 1px solid black; <?php echo $random_effect; ?>;">
</p>

<ul>
  <li>The image that was displayed was: <code><?php echo basename($random_file); ?></code></li>
  <li>The effect that was applied was: <code><?php echo $random_effect; ?></code></li>
</ul>

<p>
  <a href="/demo-harness.php?file=public/appendix-samples/random-image-with-effect.php">🔄 Get another image/effect</a>
</p>