搭建一个简单的随机图片API,支持Docker部署
搭建支持横屏、竖屏分类和 Docker 部署的随机图片 API。
约 3 分钟 全文 659 字
前言延续:随机图片 API 搭建教程
更新概览与横竖屏路由
为了同时兼容桌面端与移动端展示,新版镜像补充了按屏幕方向分流的独立接口,同时进一步压缩了容器镜像体积:
/pc路径:专门输出横屏图片(例如https://api.neix.in/random/pc)
/mobile路径:专门输出竖屏图片(例如https://api.neix.in/random/mobile)
项目特性与在线体验
随机图片 API 可以从本地图库或指定目录中动态选取一张图片返回,常用于博客随机封面、个人主页背景图或占位图场景。
- 开源仓库:Nei-Xin/random-pic-api
- 在线体验:api.neix.in/random
主要特性包括:
- 随机图片输出:每次请求从对应目录中随机抽取并返回图片流;
- 设备自适应:根据请求的 User-Agent 自动判断桌面或移动设备,分流到对应方向的图库目录;
- 多格式支持:兼容
webp、jpg、jpeg、png、gif常见图片格式。
PHP 与 Docker 部署方式
PHP 环境直接运行
如果服务器本就配置好了 PHP 与 Nginx 运行环境,将仓库源码直接放进站点根目录并挂载图片目录即可使用。
Docker Compose 部署
推荐使用容器一键部署,将宿主机整理好的横竖屏图库挂载进容器对应路径:
version: '3.9'services: random-api: image: 'neixin/random-pic-api' volumes: # 竖屏图片 - './portrait:/var/www/html/portrait' # 横屏图片 - './landscape:/var/www/html/landscape' ports: - '8080:80'图片横竖屏分流与 WebP 转换脚本
挂载图库前可以先跑一遍下方的 Python 处理脚本,它会自动识别原始素材宽高,把横屏与竖屏分开输出并统一转为 WebP 格式(运行前注意替换文件夹路径):
from PIL import Imageimport os
# 检查图片方向def get_image_orientation(image_path): with Image.open(image_path) as img: width, height = img.size return "landscape" if width > height else "portrait"
# 转换图片为 WebP 格式def convert_to_webp(image_path, output_folder, max_pixels=178956970): try: with Image.open(image_path) as img: # Check image size width, height = img.size if width * height > max_pixels: print(f"Skipping {image_path} because it exceeds the size limit.") return
# Save the image as WebP output_path = os.path.join(output_folder, os.path.splitext(os.path.basename(image_path))[0] + ".webp") img.save(output_path, "webp") except Exception as e: print(f"Failed to convert {image_path}: {e}")
# 遍历文件夹中的图片def process_images(input_folder, output_folder_landscape, output_folder_portrait): for filename in os.listdir(input_folder): if filename.endswith(('.jpg', '.jpeg', '.png')): image_path = os.path.join(input_folder, filename) orientation = get_image_orientation(image_path) try: if orientation == "landscape": convert_to_webp(image_path, output_folder_landscape) else: convert_to_webp(image_path, output_folder_portrait) except Exception as e: print(f"Error processing {image_path}: {e}. Skipping this image.")
# 指定输入和输出文件夹input_folder = "/root/photos"output_folder_landscape = "/root/landscape"output_folder_portrait = "/root/portrait"
# 执行转换process_images(input_folder, output_folder_landscape, output_folder_portrait)如果这个小工具对你刚好有帮助,欢迎去 GitHub 仓库点个 Star。
读者留言