自用 PHP 随机图片 API 源码分享(支持本地/远程/主色调提取)
今天给大家分享一个我自己在用的 PHP 随机图片 API 源码。代码非常轻量,不需要数据库,上传到网站目录即可使用。
📈 接口实时调用统计(动态图表)
以下数据直接读取服务器的 data/api_stat.json,并渲染成直观的图表(每次刷新页面数据都会变化):
🖼️ 接口图片实时预览墙
下方图片通过接口实时请求(已锁定为一行两张,固定高度裁剪,不会严重下滑):
🛠️ 接口参数说明
| 参数 | 说明 |
|---|---|
?id=1 | 远程二次元图源 |
?id=2 | 本地 dong 文件夹图片 |
?id=3 | 本地 images 文件夹图片 |
?id=4 或不填 | 全随机(1/2/3 混合) |
&type=json | 返回 JSON 格式(包含主色调) |
💻 调用示例
1. 远程二次元图:
https://yuxli.cn/api/img.php?id=1
2. 本地dong文件夹图:
https://yuxli.cn/api/img.php?id=2
3. 本地images文件夹图:
https://yuxli.cn/api/img.php?id=3
4. 全随机(1/2/3混合):
https://yuxli.cn/api/img.php
5. 返回JSON数据(含主色调):
https://yuxli.cn/api/img.php?id=3&type=json
💻 完整源码
请将以下代码保存为 img.php,上传至你网站根目录下的 api 文件夹中,并确保该文件夹有 PHP 的写入权限。统计文件会自动存放到 api/data/ 目录。
<?phpheader("Access-Control-Allow-Origin: *");header("Access-Control-Allow-Methods: GET");header('Cache-Control: no-cache, no-store, must-revalidate');header('Pragma: no-cache');header('Content-Type: application/json; charset=utf-8');// 统计文件统一放到 data 目录$dataDir = __DIR__ . '/data';if (!is_dir($dataDir)) { mkdir($dataDir, 0755, true);}$statFile = $dataDir . '/api_stat.json';$defaultStat = ['1' => 0, '2' => 0, '3' => 0, '4' => 0, 'total' => 0];function readStat($file, $default) { if (file_exists($file) && is_readable($file)) { $stat = json_decode(file_get_contents($file), true); if (is_array($stat)) return $stat; } return $default;}function addCount($id) { global $statFile, $defaultStat; $stat = readStat($statFile, $defaultStat); $stat[$id] = isset($stat[$id]) ? $stat[$id] + 1 : 1; $stat['total'] = isset($stat['total']) ? $stat['total'] + 1 : 1; if (is_writable(dirname($statFile))) { file_put_contents($statFile, json_encode($stat, JSON_UNESCAPED_UNICODE)); }}if (isset($_GET['action']) && $_GET['action'] == 'stat') { echo json_encode(readStat($statFile, $defaultStat), JSON_UNESCAPED_UNICODE); exit;}$originId = isset($_GET['id']) ? intval($_GET['id']) : 0;$id = ($originId === 0 || $originId === 4) ? mt_rand(1, 3) : $originId;addCount($id);if ($id == 1) { $apiList = [ 'https://api.r10086.com/img-api.php?type=动漫综合', 'https://img.paulzzh.com/touhou/random', 'https://api.yimian.xyz/img?type=moe' ]; foreach ($apiList as $target) { $ch = curl_init($target); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0'); $data = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $mime = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); if ($code == 200 && strpos($mime, 'image') !== false) { header("Content-Type: " . $mime); echo $data; exit; } } header("Location: https://picsum.photos/1920/1080", true, 302); exit;}if ($id == 2 || $id == 3) { $dir = $id == 2 ? 'dong/' : 'images/'; $fullDir = __DIR__ . '/' . $dir; $list = is_dir($fullDir) ? glob($fullDir . '*.{jpg,png,gif,jpeg,webp}', GLOB_BRACE) : []; if (empty($list)) { header("Location: https://picsum.photos/1920/1080", true, 302); exit; } $imgFile = $list[array_rand($list)]; $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https://' : 'http://'; $imgUrl = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/' . $dir . basename($imgFile); if (isset($_GET["type"]) && $_GET["type"] == "json") { $color = '255,255,255'; if ($id == 3 && function_exists('getimagesize')) { $info = getimagesize($imgFile); if ($info) { $ext = strtolower(substr(image_type_to_extension($info[2]), 1)); $ext = $ext == 'jpg' ? 'jpeg' : $ext; $func = 'imagecreatefrom' . $ext; if (function_exists($func)) { $img = @$func($imgFile); if ($img) { $w = imagesx($img); $h = imagesy($img); $r = $g = $b = $total = 0; $step = max(10, min($w, $h) / 50); for ($x = 0; $x < $w; $x += $step) { for ($y = 0; $y < $h; $y += $step) { $c = imagecolorat($img, $x, $y); $r += ($c >> 16) & 0xFF; $g += ($c >> 8) & 0xFF; $b += $c & 0xFF; $total++; } } imagedestroy($img); if ($total > 0) $color = round($r/$total).','.round($g/$total).','.round($b/$total); } } } } echo json_encode(['code'=>200,'imgurl'=>$imgUrl,'name'=>basename($imgFile),'color'=>$color], JSON_UNESCAPED_UNICODE); exit; } header("Location: " . $imgUrl, true, 302); exit;}header("Location: https://picsum.photos/1920/1080", true, 302);exit;—— 代码来源于网络整理优化,欢迎测试使用 ——
还行吧(*^▽^*)