第一种方法(以图片源文件进行随机)
第一步:新建一个文件夹,命名为:img(这个文件里放你需要的图片)
第二步:新建一个index.php文件,写入以下代码 (这个文件就是api地址)
<?php
$img_array = glob("img/*.{webp,gif,jpg,png}",GLOB_BRACE);
$img = array_rand($img_array);
$dz = $img_array[$img];
header("Location:".$dz);
?>
或
<?php
$img_array = glob('images/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE);
if(count($img_array) == 0) die('没找到图片文件。请先上传一些图片到 '.dirname(__FILE__).'/images/ 文件夹');
header('Content-Type: image/png');
echo(file_get_contents($img_array[array_rand($img_array)]));
?>
以上的代码会查找 images
目录下的所有图片,并随机挑选出一张显示出来。
第二种方法(以图片链接进行随机)
第一步:创建一个img.txt文件 (这个文件里放你的储存的图片链接,一行一条)
第二步:新建一个index.php文件,写入以下代码 (这个文件就是api地址)
<?php
//存有链接的文件名,这里是存放图片链接的txt文件
$filename = "img.txt";
if(!file_exists($filename)){
die('文件不存在');
}
//从文本获取链接
$pics = [];
$fs = fopen($filename, "r");
while(!feof($fs)){
$line=trim(fgets($fs));
if($line!=''){
array_push($pics, $line);
}
}
//从数组随机获取链接
$pic = $pics[array_rand($pics)];
//返回指定格式
$type=$_GET['type'];
switch($type){
//JSON返回
case 'json':
header('Content-type:text/json');
die(json_encode(['pic'=>$pic]));
default:
die(header("Location: $pic"));
}
感兴趣的话可以整一个
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容