萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取 Bing 每日壁紙:API 解析、圖片代理、緩存優化、每日自動更新

Bing 每日壁紙畫質高、版權清晰,是網站背景、鎖屏、API 服務的優質素材源。本文提供從**官方 API 解析**、**圖片代理輸出**、**本地緩存防盜鏈**、**定時任務自動更新**的完整實現方案。

一、官方 API 接口分析

Bing 官方未公開文檔,但通用接口穩定多年:

// 獲取壁紙元數據 (JSON)
https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN

// 參數:
// format=js      返回 JSON (默認 XML)
// idx=0          0=今天, -1=明天(預覽), 1=昨天, 最多 16 天歷史
// n=1            返回條數 (最大 8)
// mkt=zh-CN      市場/語言,影響版權信息語言

返回結構

{
  "images": [{
    "startdate": "20240115",
    "fullstartdate": "202401150800",
    "enddate": "20240116",
    "url": "/th?id=OHR.XXXX_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp",
    "urlbase": "/th?id=OHR.XXXX_1920x1080",
    "copyright": "攝影師信息 (© 著作權人)",
    "copyrightlink": "https://www.bing.com/search?q=...",
    "title": "圖片標題",
    "quiz": "/search?q=...",
    "wp": true,
    "hsh": "hash值",
    "drk": 1,
    "top": 1,
    "bot": 1,
    "hs": []
  }],
  "tooltips": { ... }
}

圖片分辨率 URL 構建

urlbase + _尺寸.jpg,常用尺寸:

  • 1920x1080 (Full HD)
  • 3840x2160 (4K UHD)
  • 1366x768, 1280x720, 1024x768
  • 移動端:720x1280, 1080x1920
$imageUrl = 'https://cn.bing.com' . $data['images'][0]['urlbase'] . '_1920x1080.jpg';

二、完整 PHP 實現類

<?php
namespace App\Service;

class BingWallpaper
{
    private const API_URL = 'https://cn.bing.com/HPImageArchive.aspx';
    private const CACHE_TTL = 86400; // 24小時
    private string $cacheDir;
    private int $timeout = 10;

    public function __construct(string $cacheDir = '')
    {
        $this->cacheDir = $cacheDir ?: sys_get_temp_dir() . '/bing_wallpaper';
        if (!is_dir($this->cacheDir)) mkdir($this->cacheDir, 0755, true);
    }

    /** 獲取壁紙信息 (含緩存) */
    public function getInfo(int $idx = 0, string $market = 'zh-CN'): ?array
    {
        $cacheFile = $this->cacheDir . "/info_{$idx}_{$market}.json";

        // 1. 檢查緩存
        if (is_file($cacheFile) && time() - filemtime($cacheFile) < self::CACHE_TTL) {
            return json_decode(file_get_contents($cacheFile), true);
        }

        // 2. 請求 API
        $url = self::API_URL . '?' . http_build_query([
            'format' => 'js',
            'idx' => $idx,
            'n' => 1,
            'mkt' => $market,
        ]);

        $context = stream_context_create([
            'http' => [
                'timeout' => $this->timeout,
                'user_agent' => 'Mozilla/5.0 (compatible; BingWallpaperBot/1.0)',
            ],
            'ssl' => ['verify_peer' => false, 'verify_peer_name' => false], // 簡化,生產建議驗證
        ]);

        $json = @file_get_contents($url, false, $context);
        if (!$json) return null;

        $data = json_decode($json, true);
        if (!isset($data['images'][0])) return null;

        // 3. 寫入緩存
        file_put_contents($cacheFile, json_encode($data), LOCK_EX);
        return $data;
    }

    /** 獲取圖片二進制內容 (用於代理輸出) */
    public function getImageBinary(string $imageUrl): ?string
    {
        // 圖片也緩存到本地,避免重複下載
        $hash = md5($imageUrl);
        $cacheFile = $this->cacheDir . "/img_{$hash}.jpg";

        if (is_file($cacheFile) && time() - filemtime($cacheFile) < self::CACHE_TTL) {
            return file_get_contents($cacheFile);
        }

        $context = stream_context_create([
            'http' => [
                'timeout' => 30,
                'header' => "Referer: https://cn.bing.com\r\n", // 防盜鏈
            ],
        ]);

        $content = @file_get_contents($imageUrl, false, $context);
        if ($content) {
            file_put_contents($cacheFile, $content, LOCK_EX);
        }
        return $content;
    }

    /** 直接輸出圖片到瀏覽器 (代理模式) */
    public function outputImage(int $idx = 0, string $resolution = '1920x1080'): void
    {
        $info = $this->getInfo($idx);
        if (!$info) {
            http_response_code(404);
            exit('Wallpaper not found');
        }

        $imageUrl = 'https://cn.bing.com' . $info['images'][0]['urlbase'] . "_{$resolution}.jpg";
        $binary = $this->getImageBinary($imageUrl);
        if (!$binary) {
            http_response_code(502);
            exit('Failed to fetch image');
        }

        // 輸出頭
        header('Content-Type: image/jpeg');
        header('Content-Length: ' . strlen($binary));
        header('Cache-Control: public, max-age=86400'); // 客戶端緩存 1 天
        header('ETag: "' . md5($binary) . '"');
        header('Content-Disposition: inline; filename="bing_' . $info['images'][0]['startdate'] . '_{$resolution}.jpg"');

        // 條件請求支持
        if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === '"' . md5($binary) . '"') {
            http_response_code(304);
            exit;
        }

        echo $binary;
        exit;
    }

    /** 獲取版權信息用於前端顯示 */
    public function getCopyright(int $idx = 0): string
    {
        $info = $this->getInfo($idx);
        return $info['images'][0]['copyright'] ?? '© Bing';
    }
}

三、使用示例

1. 直接輸出圖片 (作為 <img src="wallpaper.php">)

<?php
// wallpaper.php
require 'vendor/autoload.php';
$wallpaper = new \App\Service\BingWallpaper();
$wallpaper->outputImage(0, '1920x1080');

2. 前端頁面嵌入 (含版權信息)

<?php
$wallpaper = new \App\Service\BingWallpaper();
$info = $wallpaper->getInfo();
$imgUrl = 'wallpaper.php'; // 代理地址
$copyright = $wallpaper->getCopyright();
?>
<div class="bing-wallpaper">
    <img src="<?php echo $imgUrl; ?>" alt="Bing 每日壁紙" loading="lazy">
    <div class="copyright"><?php echo htmlspecialchars($copyright); ?></div>
</div>

3. API 接口返回 JSON (前端分離)

<?php
// api/bing-wallpaper.php
header('Content-Type: application/json; charset=UTF-8');
$wallpaper = new \App\Service\BingWallpaper();
$info = $wallpaper->getInfo();
if ($info) {
    $img = $info['images'][0];
    echo json_encode([
        'date' => $img['startdate'],
        'title' => $img['title'],
        'copyright' => $img['copyright'],
        'copyright_link' => 'https://cn.bing.com' . $img['copyrightlink'],
        'urls' => [
            '1920x1080' => 'https://cn.bing.com' . $img['urlbase'] . '_1920x1080.jpg',
            '3840x2160' => 'https://cn.bing.com' . $img['urlbase'] . '_3840x2160.jpg',
            '720x1280'  => 'https://cn.bing.com' . $img['urlbase'] . '_720x1280.jpg',
        ],
    ], JSON_UNESCAPED_UNICODE);
} else {
    http_response_code(503);
    echo json_encode(['error' => 'Failed to fetch']);
}

四、定時任務預熱緩存 (Cron)

# 每天凌晨 3 點預熱今天和明天的壁紙信息及圖片
0 3 * * * /usr/bin/php /path/to/project/cli/preload_bing.php

# cli/preload_bing.php
<?php
require 'vendor/autoload.php';
$wallpaper = new \App\Service\BingWallpaper();
foreach ([0, -1] as $idx) { // 今天、明天預覽
    $wallpaper->getInfo($idx); // 觸發緩存寫入
    // 可選:預下載常用分辨率圖片
    $info = $wallpaper->getInfo($idx);
    if ($info) {
        foreach (['1920x1080', '3840x2160', '720x1280'] as $res) {
            $url = 'https://cn.bing.com' . $info['images'][0]['urlbase'] . "_{$res}.jpg";
            $wallpaper->getImageBinary($url);
        }
    }
}
echo "Bing wallpaper cache warmed up.\n";

五、法律與道德提醒

  • 版權歸屬: 圖片版權屬於攝影師/微軟,copyright 字段必須保留顯示。
  • 使用條款: 僅限**個人非商業用途**(桌面壁紙、個人博客背景)。商業用途、大規模分發、去版權均屬侵權。
  • 防盜鏈: Bing 圖片有 Referer 檢查,直接 <img src="https://cn.bing.com/...> 可能 403,**必須代理輸出**或設置 referrerpolicy="no-referrer" (但可能仍被攔截)。
  • 頻率限制: 不要高頻請求 API,每天 1-2 次足夠,緩存 24 小時。

總結

Bing 每日壁紙接口穩定、畫質高,通過 **API 解析 → 本地緩存 (信息+圖片) → 代理輸出 → 定時預熱** 的完整鏈路,可構建高可用、合規、高性能的壁紙服務。核心代碼約 100 行,無第三方依賴,易於集成到任何 PHP 項目。

copyright © 萬盛學電腦網 all rights reserved