4 种技术方案打造随机图片站:从入门到进阶

冯马佑 📋在职小初生

无论你是想搭建 壁纸站趣味图库,还是为博客增加 随机头图 功能,本教程提供 4 种技术方案,涵盖:

✅ 纯前端静态方案(适合新手)
✅ 云函数代理方案(适合中小型项目)
✅ 自建后端 API 方案(适合企业级应用)
✅ 无服务器跳转方案(适合极客玩家)


1. 方案对比:如何选择最适合你的技术路线?

方案 所需技能 成本 适合人群
纯前端方案 HTML / JS 免费 个人博客 / 新手
云函数代理 云服务 / JS 中小型项目
自建后端 API Node.js + 运维 企业 / 技术团队
无服务器跳转 Nginx 配置 免费 极客 / SEO 不敏感场景

2. 纯前端方案:快速搭建

2.1 核心代码(适用于 GitHub Pages / Vercel)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<title>随机图片站</title>
<meta name="description" content="一个轻量级的随机壁纸网站,每次刷新都不同!">
<meta name="keywords" content="壁纸, 随机图片, 图片 API, 免费图片资源">
<style>
img { max-width: 100%; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
</style>
</head>
<body>
<img id="randomImg" src="" alt="随机图片">
<script>
const images = [
"https://source.unsplash.com/random/1920x1080?nature",
"https://source.unsplash.com/random/1920x1080?city",
"https://source.unsplash.com/random/1920x1080?animal"
];

function loadImage() {
const imgElement = document.getElementById('randomImg');
imgElement.src = images[Math.floor(Math.random() * images.length)] + "&t=" + Date.now();
}

loadImage();
setInterval(loadImage, 10000);
</script>
</body>
</html>

2.2 部署步骤

  1. 保存为 index.html
  2. 上传至 GitHub 仓库
  3. 开启 GitHub Pages 服务

2.3 方案特点

优点 缺点
5 分钟快速上线 需手动维护图片列表
完全免费 URL 暴露,容易被采集
无服务器依赖 无法动态扩展

3. 云函数代理方案(Cloudflare Worker)

3.1 架构

graph TD;
A[用户] --> B[访问 Cloudflare Worker] --> C[Worker 随机选择图片] --> D[返回图片内容]

3.2 Cloudflare Worker 代码

1
2
3
4
5
6
7
8
9
10
11
12
const IMAGE_SOURCES = [
"https://lsky-pro.com/images/1.jpg",
"https://oss.aliyuncs.com/bucket/2.png",
"https://img.usercontent.com/3.webp"
];

export default {
async fetch() {
const targetUrl = IMAGE_SOURCES[Math.floor(Math.random() * IMAGE_SOURCES.length)];
return fetch(targetUrl, { headers: { "Cache-Control": "public, max-age=7200" } });
}
};

4. 自建后端 API(专业版)

4.1 系统架构

graph TD;
A[用户请求] --> B[Nginx] --> C[Node.js API] --> D[Lsky Pro 图床]

4.2 Node.js API 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

let cachedImages = [];
let lastUpdate = 0;

async function refreshImages() {
try {
const res = await fetch('https://lsky.yourdomain.com/api/v1/images?per_page=100');
const data = await res.json();
cachedImages = data.data.map(img => img.links.url);
lastUpdate = Date.now();
} catch (error) {
console.error('刷新图片失败:', error);
}
}

setInterval(refreshImages, 300000);

app.get('/random', async (req, res) => {
if (Date.now() - lastUpdate > 300000) { await refreshImages(); }
if (cachedImages.length === 0) { return res.status(503).json({ error: "服务暂不可用" }); }
res.redirect(302, cachedImages[Math.floor(Math.random() * cachedImages.length)]);
});

app.listen(3000, () => console.log('API 运行于 http://localhost:3000'));

5. 无服务器跳转(极客玩法)

5.1 Nginx 伪装跳转

1
2
3
4
5
6
server {
listen 80;
server_name img.yourdomain.com;
location = /random.jpg { rewrite ^ /random.html break; }
location / { root /var/www/static; index index.html; }
}

5.2 HTML 页面自动跳转

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head><title>随机图片跳转</title>
<script>
fetch('/image-list.json').then(res => res.json()).then(images => {
window.location.href = images[Math.floor(Math.random() * images.length)] + '?t=' + Date.now();
});
</script>
</head>
<body><p>正在加载随机图片...</p></body>
</html>

6. 终极优化:速度与安全

6.1 缓存策略

层级 方案
浏览器 Cache-Control: max-age=86400
CDN Cloudflare 缓存规则
服务端 Redis 缓存图片列表

6.2 防盗链设置

1
2
valid_referers none blocked *.yourdomain.com;
if ($invalid_referer) { return 403; }

本教程提供从 0 到 1 的完整方案,适用于不同技术水平的开发者,赶快试试吧!🚀

  • 标题: 4 种技术方案打造随机图片站:从入门到进阶
  • 作者: 冯马佑
  • 创建于 : 2025-03-09 19:36:20
  • 更新于 : 2025-03-09 22:53:42
  • 链接: https://blog.fengmayou.top/2025/03/09/Random-plots/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论