如何选择大小在100-500kb之间的图像



我有一个简短的PHP代码来帮助我显示特定文件夹中的随机图像。但现在它似乎可以选择任何大小的任何图像。我希望那些选择的图像在100-500kb之间。如果它小于100kb或超过500kb,函数将不会选择和显示它。你能告诉我如何修改这个代码吗?可能需要添加一些功能。

<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
}
$random = mt_rand(1, $count - 1); 
echo '<img src="images/random/'.$imagearray[$random].'" alt />';
?>

试试这个我们必须设置两个条件

$min =  100; //KB
$max = 500; //KB
if($_FILES['myfile']['size'] < $min * 1024 || $_FILES['myfile']['size'] > $max * 1024){
echo 'error';
}

立即试用

<?php 
$dir_name = 'images/random/';
$pattern="/(gif|jpg|jpeg|png)/";
$min = 100;
$max = 500;
$imagearray = array();
$scanned_directory = array_diff(scandir($dir_name), array('..', '.'));
$count = count($scanned_directory);
$ids = array_keys($scanned_directory);

$s = TRUE;
$stop = $count;
while( ($s === TRUE) && ($stop >=0))
{


$random = mt_rand(0, $count - 1);
$full_path_to_file = $dir_name.$scanned_directory[$ids[$random]];
$ext = pathinfo($full_path_to_file, PATHINFO_EXTENSION);
$file_size_kb = round(filesize($full_path_to_file)/1024);
if (preg_match($pattern, $ext) && ($file_size_kb>=$min && $file_size_kb<=$max)) 
{
$s = FALSE;
echo '<img src="'.$full_path_to_file.'" alt />';
}
$stop--;
}
?>

最新更新