Login
1 条评论
空空如也~
Loading...
- 分享一个随机输出图片API(PHP)
这是一个简单的脚本,用于从您设置的文件夹中随机选择图像,您可以在博客背景、个人网站或您喜欢的任何内容上使用它 O3O
搭建准备
1️⃣ 先创建一个文件夹 命名为img(里面存放你的照片)
2️⃣ 创建index.php 把PHP代码复制进去保存
3️⃣ 大功告成
PHP代码
define("IMG_DIR",'img/');
define("IMG_EXTENSIONS",'*.{jpg,jpeg,png}');
define("IMG_NO_REPEAT_CURRENT",true);
function randomSelectIndex() {
$imgs = glob(IMG_DIR . IMG_EXTENSIONS, GLOB_BRACE);
$selectedIndex = array_rand($imgs);
setcookie("currentIndex", $selectedIndex);
return $selectedIndex;
}
function getImgFromIndex($index) {
$imgs = glob(IMG_DIR . IMG_EXTENSIONS, GLOB_BRACE);
if(IMG_NO_REPEAT_CURRENT && isset($_COOKIE['currentIndex'])):
while ($index == $_COOKIE['currentIndex']):
$index = randomSelectIndex();
endwhile;
endif;
$randomImage = $imgs[$index];
return $randomImage;
}
$currentSelectedIndex = randomSelectIndex();
$randomImage = getImgFromIndex($currentSelectedIndex);
header('Content-Type:image/jpeg');
header('Content-Length: ' . filesize($randomImage));
readfile($randomImage);
代码说明
MG_DIR - Web 服务器中图像文件夹的相对路径。
IMG_EXTENSIONS - 图像支持的图像文件扩展名。
IMG_NO_REPEAT_CURRENT - 如果设置为true下一个随机选择的图像将与当前选择的图像不同,如果设置为false将忽略当前选择的图像进行下一个随机选择(因此可能会出现重复选择的图像
暂无评论 >_<