465 字
2 分钟
随机图片API
自建
使用PHP自建
-
方法一:直接返回图片
<?php$img_array = glob('image/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE);/*遍历文件并赋值给数组*/if(count($img_array) == 0) die('赶紧上传图片 '.dirname(__FILE__).'/images/ 文件夹');/*检测文件夹中是否有文件*/header('Content-Type: image/png');/*设置响应类型*/echo(file_get_contents($img_array[array_rand($img_array)]));/*响应图片*/?> -
方法二:返回图片URL并重定向(应该可以防止客户端使用缓存,导致图片无法随机)
<?php// 图片文件夹路径$images_folder = 'path/to/image/';// 随机生成一个图片文件名$random_image_name = 'random_image_' . md5(time()) . '.jpg';// 在图片文件夹中随机选择一张图片$random_image_path = $images_folder . $random_image_name;// 如果文件夹中没有图片,返回错误if (!is_dir($images_folder) empty(glob($images_folder . '*'))) {die('No images found in the folder "' . $images_folder . '"');}// 如果随机图片文件已经存在,返回它if (file_exists($random_image_path)) {$image = file_get_contents($random_image_path);echo $image;exit;}// 如果随机图片文件不存在,就随机选择一张图片生成一个新文件$files = glob($images_folder . '*');$random_image_index = rand(0, count($files) - 1);$random_image = $files[$random_image_index];copy($random_image, $random_image_path);// 在请求结束后删除生成的图片文件register_shutdown_function(function() use ($random_image_path) {if (file_exists($random_image_path)) {unlink($random_image_path);}});$image = file_get_contents($random_image_path);header('Content-Type: image/png');header("Location: /$random_image_path");// echo $image;?>
实现图片自适应
如果想根据设备或者说横竖屏来返回图片,可以把以上方法的代码嵌入到以下判断中,根据不同是设备方向返回不同的文件目录
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// 判断是否为移动设备if (strpos($user_agent, 'Mobile') !== false) { // 判断屏幕方向 if (strpos($user_agent, 'Landscape') !== false) { echo '横屏'; } else { echo '竖屏'; }} else { echo '非移动设备';}
我搭建的(部署在Replit)
网上收集到的
雫 API
正常复制请求地址当做图片链接来用就行
适用设备
请求方式
请求地址
1
电脑
Get
2
手机
Get