搭建一个随机图片api
图片分类,并转化为webp格式
最近在搭建随机图片api过程中,想到将图片横屏和竖屏区分开,这样更适配手机和电脑,并将图片转化为webp格式,可以加载的更快,注意修改图片路径,python代码如下
from PIL
import Image
import 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):
with Image.open(image_path) as img:
output_path = os.path.join(output_folder, os.path.splitext(os.path.basename(image_path))[0] + ".webp")
img.save(output_path, "webp")
# 遍历文件夹中的图片
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)
if orientation == "landscape":
convert_to_webp(image_path, output_folder_landscape)
else:
convert_to_webp(image_path, output_folder_portrait)
# 指定输入和输出文件夹
input_folder = "/root/data/alist/local/photos"
output_folder_landscape = "/root/data/alist/local/landscape"
output_folder_portrait = "/root/data/alist/local/portrait"
# 执行转换
process_images(input_folder, output_folder_landscape, output_folder_portrait)
php代码
可以自动识别手机端和电脑端,创建landscape和portrait文件夹,分别存放横屏和竖屏图片
<?php
// 设置站点地址
$weburl = 'https://api.zzii.de/';
$pcPath = 'landscape';
$mobilePath = 'portrait';
// 函数:从目录中获取图片列表
function getImagesFromDir($path) {
$images = array();
if ($img_dir = @opendir($path)) {
while (false !== ($img_file = readdir($img_dir))) {
if (preg_match("/(\.webp)$/", $img_file)) { // 仅匹配 WebP 格式的图片
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}
// 检测用户代理以区分手机和电脑访问
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$isMobile = preg_match('/(android|iphone|ipad|ipod|blackberry|windows phone)/i', $userAgent);
// 根据访问设备设置图片路径
if ($isMobile) {
$path = $mobilePath;
} else {
$path = $pcPath;
}
// 缓存图片列表
$imgList = getImagesFromDir($path);
// 从列表中随机选择一张图片
shuffle($imgList);
$img = reset($imgList);
// 直接输出所选的随机图片
$img_path = $path . '/' . $img;
$img_url = $weburl . $img_path;
header('Content-Type: image/webp'); // 设置 Content-Type 为 image/webp
readfile($img_path);
?>
最后
给一个我搭建的成果吧:https://api.zzii.de/random/