Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
311 字
2 分钟
随机背景图api
2025-12-22

# 前言#

网上其实可以搜到很多关于随机图片的 API,但是大部分已经长时间没有维护,并且返回的图片很多也一言难尽,因此考虑自建一个专属的图库 API,自己挑选整理图片,不喜欢也可以随时更换。

本次使用的是 Git 托管图片+Rust 来构建

实现#

整理图片#

  1. 首先准备好自己的图库,并对图片进行重命名,以便后续管理
  2. 创建一个文本储存所有图片地址
  3. 将图片推送到 git 仓库

API#

服务器创建一个 API 脚本,用于直接返回图片,这里使用 rust 实现

#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
use rand::seq::SliceRandom;
use reqwest::blocking::get;
use rocket::response::Redirect;
#[get("/random-background")]
fn random_background() -> Redirect {
// 获取file_list.txt文件的内容
let response = get("git地址/file_list.txt")
.expect("Failed to fetch file_list.txt");
// 按行分割文件内容,得到一个图片URL列表
let response_text = response.text().expect("Failed to read response");
let backgrounds: Vec<_> = response_text.split('\n').collect();
// 从列表中随机选择一张图片
let background = backgrounds
.choose(&mut rand::thread_rng())
.expect("Failed to choose a background");
// 返回一个重定向到随机选择的图片URL
Redirect::to(background.to_string())
}
fn main() {
// 绑定端口
std::env::set_var("ROCKET_PORT", "8000");
rocket::ignite().mount("/api/", routes![random_background]).launch();
}

[00. 代码库]({{< ref “00. 代码库” >}})

随机背景图api
https://blog.evebreeze.top/posts/随机背景图api/
作者
晚风
发布于
2025-12-22
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00