前言
我的Alist云盘背景为随机展示的图片,后台需要填写随机图片api地址,但是网上各种api提供的图片都不是很合胃口,而且清晰度也不高,于是决定还是自己搭建一个,放上自己喜欢的图片链接。DEMO
:https://image.api.kafuchino.top
正式开始
Github上有很多类似的项目,能实现图片分类成摄影、动漫、风景等多种接口,不过笔者只想轻度使用,只需要二次元
这个分类,因此选择了这个简易的Random-Picture,可以直接一键部署在vercel上。
部署Random-Picture到vercel
点击
Deploy
,转到自己的vercel部署项目 填写一个仓库名称,点击
Create
等待几秒网页就创建好了

不过原作者的这个并没有检测设备类型的功能,电脑大小的壁纸在手机上的显示效果并不好,因此稍加修改
添加自适应设备功能
当然你懒得改可以直接fork我的仓库部署random-picture

根目录添加文件moburl.csv
,内容是手机比例的壁纸图片链接

修改文件api/index.php
,代码如下:
php
<?php
const ALLOW_RAW_OUTPUT = false;
// 是否开启 ?raw 选项,可能会消耗服务器较多流量
function has_query($query) {
return isset($_GET[$query]);
}
function is_mobile() {
// 简单的 User-Agent 检测方法
return preg_match('/mobile|android|iphone|ipod|ipad|windows phone/i', $_SERVER['HTTP_USER_AGENT']);
}
// 根据设备类型选择不同的 CSV 文件
if (is_mobile()) {
$csv_file = 'moburl.csv'; // 手机壁纸
} else {
$csv_file = 'url.csv'; // 电脑壁纸
}
// 加载 CSV 文件
if (file_exists(__DIR__ . '/' . $csv_file)) // in the same folder
$imgs_array = file(__DIR__ . '/' . $csv_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
else if (file_exists('../' . $csv_file)) // in the parent folder
$imgs_array = file('../' . $csv_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
else // for vercel runtime or if the file does not exist
$imgs_array = file('http://' . $_SERVER['HTTP_HOST'] . '/' . $csv_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// 如果 CSV 文件没有加载到任何 URL,则使用备用图片
if (count($imgs_array) == 0) $imgs_array = array('https://http.cat/503');
$id = has_query('id') ? $_GET['id'] : "";
if (strlen($id) > 0 && is_numeric($id)) {
settype($id, 'int');
$len = count($imgs_array);
if ($id >= $len || $id < 0) {
$id = array_rand($imgs_array);
} else {
header('Cache-Control: public, max-age=86400');
}
} else {
header('Cache-Control: no-cache');
$id = array_rand($imgs_array);
}
if (has_query('json')) {
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode(array('id' => $id, 'url' => $imgs_array[$id]));
} else if (has_query('raw')) {
if (!ALLOW_RAW_OUTPUT) {
header('HTTP/1.1 403 Forbidden');
exit();
}
header('Content-Type: image/png');
echo file_get_contents($imgs_array[$id]);
} else {
header('Referrer-Policy: no-referrer');
header('Location: ' . $imgs_array[$id]);
}
exit();
保存,vercel 会自动部署。这时访问部署好的api地址,就可以实现自适应随机壁纸了
推荐添加自己的域名

后记
至于如何获取稳定图片直链,方法有很多,比如Alist
、CF搭建图床
、B站图床
等。笔者这里是把图片都放到了腾讯云新出的Pages
上,访问速度很快还免费,有兴趣的可以尝试:腾讯云Pages
- 本文链接:https://blog.kafuchino.top/posts/2024-09-30
- 版权声明:本博客所有文章除特别声明外,均默认采用 CC BY-NC-SA 许可协议。