自建 Bing 每日图片 API

本文适合想给自己的站点提供 Bing 每日图片接口的开发者。你会学到:用一段 PHP 脚本代理 Bing 每日壁纸接口,支持随机模式(rand=true)、自定义分辨率(size)和 JSON 信息返回(info=true),并用 Nginx 部署。

PHP 代码

<?php
// 判断是否启用随机模式(rand=true)
$idx = (isset($_GET['rand']) && $_GET['rand'] === 'true') ? rand(0, 7) : 0;
// 获取 Bing 图片 JSON 数据
$json = @file_get_contents("https://www.bing.com/HPImageArchive.aspx?format=js&idx=$idx&n=1");
if ($json === false) {
    http_response_code(500);
    echo "无法获取 Bing 图片数据";
    exit;
}
// 解码 JSON
$data = json_decode($json);
$image = $data->images[0];
// 获取分辨率参数,默认 1920x1080
$size = empty($_GET['size']) ? "1920x1080" : $_GET['size'];
// 拼接完整图片 URL
$imageUrl = "https://www.bing.com" . $image->urlbase . "_{$size}.jpg";
// 获取其他信息
$title = $image->copyright;
$link  = $image->copyrightlink;
$time  = $image->startdate;
// 判断是否仅返回信息(info=true)
if (isset($_GET['info']) && $_GET['info'] === 'true') {
    header("Content-Type: application/json");
    echo json_encode([
        "title" => $title,
        "url"   => $imageUrl,
        "link"  => $link,
        "time"  => $time
    ]);
} else {
    // 否则重定向到图片地址
    header("Location: $imageUrl");
    exit;
}

Nginx 配置文件

server {
    listen 127.0.0.1:60080;
    
    root /var/www/html;
    index index.php index.html;
    location / {
        try_files $uri $uri/ =404;
    }
    # 处理 PHP 文件
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;  # 这里根据你的 PHP 版本可能不同
    }
    location ~ /\.ht {
        deny all;
    }
}

使用方法

使用 url https://yourdomain.com?rand=true

验证与自查

  1. curl -I 'https://yourdomain.com' 返回 302Location 指向 https://www.bing.com/... 图片地址
  2. curl -I 'https://yourdomain.com?rand=true' 多次执行返回不同的图片 URL
  3. curl 'https://yourdomain.com?info=true' 返回包含 title/url/link/time 的 JSON
  4. size 参数(如 ?size=1920x1200)能拿到对应分辨率图片

参考