第一种方法(以图片源文件进行随机)
步骤
- 新建一个文件夹,命名为:img(这个文件里放你需要的图片)
- 新建一个index.php文件,写入以下代码 (这个文件就是api地址)
代码
<?php
$img_array = glob('img/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE);
if(count($img_array) == 0) die('没找到图片文件。请先上传一些图片到 '.dirname(__FILE__).'/img/');
header('Content-Type: image/png');
echo(file_get_contents($img_array[array_rand($img_array)]));
?>
第二种方法(以图片链接进行随机)
步骤
- 创建一个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"));
}