必應每日桌布API封裝

落水的月亮發表於2024-09-06

簡介

這個類封裝了必應首頁的每日桌布檢視功能,提供了檢視、儲存桌布的方法,最大支援檢視近8天的桌布

使用方法

async Task Main()
{
	try
	{
		var bing = BingWallpaperAPI.CreateInstance(8); //初始化,引數8表示一共會載入8張圖片
		var task = await bing.Current();
		task.Wallpaper.Dump();  //載入桌布
		Console.WriteLine("日期\t" + task.EndDate);
		Console.WriteLine("標題\t" + task.Title);  //載入相關資訊
		Console.WriteLine("版權\t" + task.Copyright);
		Console.WriteLine("連結\t" + task.CopyrightLink);
		if (await bing.SaveCurrentWallpaper(@"D:\bing.jpg"))	//儲存當前的桌布
		{
			Console.WriteLine("儲存成功");
		};
		var task1 = await bing.Next();  //載入下一張桌布
		task1.Wallpaper.Dump(); //列印桌布
		var task2 = await bing.Previous();  //載入上一張桌布
		task2.Wallpaper.Dump(); //列印桌布
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}
}

效果預覽


API封裝

點選檢視程式碼
using System;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

   /// <summary>
   /// 載入Bing桌布,單例,使用CreateInstance方法建立類的例項
   /// </summary>
   public sealed class BingWallpaperAPI
   {
       private static BingWallpaperAPI _instance = null;
       private static readonly object _padlock = new Object();
       /// <summary>
       /// 建立類的例項
       /// </summary>
       /// <param name="imgnums">桌布的張數,可以是1-8之間的數</param>
       /// <returns></returns>
       public static BingWallpaperAPI CreateInstance(byte imgnums = 3)
       {
           if (_instance is null)
           {
               lock (_padlock)
               {
                   if (_instance is null) _instance = new BingWallpaperAPI(imgnums);
               }
           }
           return _instance;
       }
       private BingWallpaperAPI(byte imgnums)
       {
           if (imgnums > 8 || imgnums <= 0)
           {
               _imgnums = 3;
               Debug.WriteLine($"僅支援1-8張圖片,你輸入的{imgnums}被重置為3");
           }
           else { _imgnums = imgnums; }
           GetWallpaperLink();
       }
       /// <summary>內建索引</summary>
       private int _index = -1;
       /// <summary>
       /// 載入Bing桌布的數量,預設為3
       /// </summary>
       private static byte _imgnums;
       private BingApiModel _bingApiModel;
       /// <summary>
       /// 載入桌布的JSON格式檔案,檔案中包含了桌布的下載地址等關鍵資訊
       /// </summary>
       /// <exception cref="Exception"></exception>
       private void GetWallpaperLink()
       {
           HttpClient client = new HttpClient();
           for (int i = 0; i < 3; i++) //這個步驟會嘗試3次
           {
               try
               {
                   var res = client.GetAsync($"https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n={_imgnums}&mkt=zh-CN").Result;
                   //引數n:1-8 返回請求數量,目前最多一次獲取8張
                   //引數format:js/xml
                   //引數idx:請求圖片截止天數 0 今天;1 截止至昨天,類推(目前最多獲取到7天前的圖片)
                   //引數mkt:地區
                   var json = res.Content.ReadAsStringAsync().Result;
                   BingApiModel bingApiModel = new BingApiModel();
                   _bingApiModel = JsonSerializer.Deserialize<BingApiModel>(json);
                   ImageCount = _bingApiModel.images.Count();
                   if (ImageCount == _imgnums)
                   {
                       break;  //載入成功時直接終止迴圈
                   }
               }
               catch (Exception ex)
               {
                   if (i == 2) { throw ex; } else Console.WriteLine(ex.Message);
               }
           }
       }
       /// <summary>
       /// 根據JSON資料下載桌布
       /// </summary>
       /// <param name="index">_bingApiModel索引</param>
       /// <returns></returns>
       /// <exception cref="Exception"></exception>
       private async Task<BingWallpaper> GetWallpaper(int index)
       {
           try
           {
               using (HttpClient client = new HttpClient())
               {
                   var element = _bingApiModel.images[index];
                   var res = await client.GetAsync("https://cn.bing.com" + element.url);
                   //這個URL中的第一個1920x1080改成UHD是4k
                   var imgStream = await res.Content.ReadAsStreamAsync();
                   return (new BingWallpaper()
                   {
                       Wallpaper = System.Drawing.Image.FromStream(imgStream),
                       Title = element.title,
                       Copyright = element.copyright,
                       CopyrightLink = element.copyrightlink,
                       EndDate = element.enddate,
                   });
               }
           }
           catch (Exception ex)
           {
               throw ex;
           }
       }
       /// <summary>
       /// 載入JSON資料包含的URL數量
       /// </summary>
       public int ImageCount { get;private set; }
       /// <summary>
       /// 下一張桌布
       /// </summary>
       /// <returns></returns>        
       /// <exception cref="Exception"></exception>
       public async Task<BingWallpaper> Next()
       {
           if (ImageCount == 0)
           {
               return null;
           }
           _index++;
           if (_index >= ImageCount)   //重置索引
           {
               _index = 0;
           }
           return await GetWallpaper(_index);
       }
       /// <summary>
       /// 上一張桌布
       /// </summary>
       /// <returns></returns>
       /// <exception cref="Exception"></exception>
       public async Task<BingWallpaper> Previous()
       {
           if (ImageCount == 0)
           {
               return null;
           }
           _index--;
           if (_index < 0)
           {
               _index = ImageCount - 1;    //重置索引
           }
           return await GetWallpaper(_index);
       }

       /// <summary>
       /// 儲存當前的桌布到本地
       /// </summary>
       /// <param name="path">儲存的路徑、含檔名(如c:\1.jpg),格式為JPEG</param>
       /// <returns>儲存是否成功</returns>
       /// <exception cref="Exception"></exception>
       public async Task<bool> SaveCurrentWallpaper(string path)
       {
           try
           {
               var task = await Current();
               task.Wallpaper.Save(path, ImageFormat.Jpeg);
               return true;
           }
           catch (Exception ex)
           {
               throw ex;
           }
       }
       /// <summary>
       /// 當前桌布
       /// </summary>
       /// <returns></returns>
       /// <exception cref="Exception"></exception>
       public async Task<BingWallpaper> Current()
       {
           if (ImageCount == 0)
           {
               return null;
           }
           if (_index == -1)
           {
               _index = 0;
           }
           return await GetWallpaper(_index);
       }
   }
   /// <summary>
   /// 用來儲存桌布資訊的類模型
   /// </summary>
   public class BingWallpaper
   {
       /// <summary>桌布</summary>
       public System.Drawing.Image Wallpaper { get; set; }
       /// <summary>標題</summary>
       public string Title { get; set; }
       /// <summary>版權</summary>
       public string Copyright { get; set; }
       /// <summary>版權連結</summary>
       public string CopyrightLink { get; set; }
       /// <summary>
       /// 桌布所屬日期
       /// </summary>
       public string EndDate { get; set; }
   }
   /// <summary>
   /// 用來解析JSON資料的類模型
   /// </summary>
   public class BingApiModel
   {
       /// <summary>
       /// 返回圖片集合
       /// </summary>
       public Image[] images { get; set; }
   }
   public class Image
   {
       /// <summary>
       /// 每日桌布的日期
       /// </summary>
       public string enddate { get; set; }
       /// <summary>
       /// 桌布的地址
       /// </summary>
       public string url { get; set; }
       /// <summary>桌布的簡述、拍攝地址(攝影人)</summary>
       public string copyright { get; set; }
       /// <summary>桌布相關搜尋連結</summary>
       public string copyrightlink { get; set; }
       /// <summary>桌布的標題</summary>
       public string title { get; set; }
   }

原創宣告

作者:落水的月亮
出處:部落格園
轉載:可以轉載,轉載必須註明出處。必須在文章中給出原文連線。


必應主頁

相關文章