Anna Riekic
Anna Riekic

Reputation: 183

php random image where width equals

I currently have this snippet which spits out a random image

$imgDir  = 'images/';
$images  = glob($imagesDir . '*.{jpg}', GLOB_BRACE);
$randimg = $images[array_rand($images)];

but I want the image to be a certain width (600px), rather then warping images by using CSS is there a way the image width can be checked using PHP incorporating the code snippet above?

Upvotes: 0

Views: 159

Answers (2)

bkwint
bkwint

Reputation: 626

This will make sure you only select a random images from the images that have width 600

$imgDir = 'images/';
$images = glob($imgDir . '*.{jpg}', GLOB_BRACE);

$arr_images_600 = array();
foreach ($images as $img)
{
  list($width, $height, $type, $attr) = getimagesize($img);
  if ($width == 600) { $arr_images_600[] = $img; }
}
$randimg = $images[array_rand($arr_images_600)];

Upvotes: 0

deceze
deceze

Reputation: 522016

Yes, you can go through each individual file and check its size with getimagesize.

That's of course a very expensive operation to do every time. Instead, do this once and make the size part of the filename (e.g. foobar_500.jpg) and glob for that, or use a database to organize your images to begin with where you can save such metadata and query for it.

Upvotes: 3

Related Questions