Reputation: 23
I'm doing some web development I would like to resize all images in a directory using PHP. The directory is public property, and anyone working on the site can insert images (to be used as a random background). Is there a way to check the size of the image that's selected from the array of filenames using PHP? And furthermore, could you cast the image to a particular size if the parameters are too large?
<?php
$bg = glob("imgfiles/*.*"); $add image names to array
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set background equal to which random filename was chosen
?>
Upvotes: 2
Views: 1001
Reputation: 30899
So I would suggest something like:
<?php
$maxw = 1024;
$maxh = 320;
$bg = glob("./imgfiles/*.*"); // add image names to array
$selectedBgPath = "./imgfiles/" . $bg[array_rand($bg)]; // set background path equal to which random filename was chosen
list($width, $height, $type, $attr) = getimagesize($selectedBgPath);
if($width > $maxw || $height > $maxh){
// Resize as needed
// $newSelectedBgPath
}
if(isset($newSelectedBgPath)){
$fp = fopen($newSelectedBgPath, "rb");
} else {
$fp = fopen($selectedBgPath, "rb");
}
header("Content-type: $type");
fpassthru($fp);
exit;
?>
Upvotes: 1