翼度科技»论坛 编程开发 .net 查看内容

必应每日壁纸API封装

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
简介

这个类封装了必应首页的每日壁纸查看功能,提供了查看、保存壁纸的方法,最大支持查看近8天的壁纸
使用方法
  1. async Task Main()
  2. {
  3.         try
  4.         {
  5.                 var bing = BingWallpaperAPI.CreateInstance(8); //初始化,参数8表示一共会加载8张图片
  6.                 var task = await bing.Current();
  7.                 task.Wallpaper.Dump();  //加载壁纸
  8.                 Console.WriteLine("日期\t" + task.EndDate);
  9.                 Console.WriteLine("标题\t" + task.Title);  //加载相关信息
  10.                 Console.WriteLine("版权\t" + task.Copyright);
  11.                 Console.WriteLine("链接\t" + task.CopyrightLink);
  12.                 if (await bing.SaveCurrentWallpaper(@"D:\bing.jpg"))        //保存当前的壁纸
  13.                 {
  14.                         Console.WriteLine("保存成功");
  15.                 };
  16.                 var task1 = await bing.Next();  //加载下一张壁纸
  17.                 task1.Wallpaper.Dump(); //打印壁纸
  18.                 var task2 = await bing.Previous();  //加载上一张壁纸
  19.                 task2.Wallpaper.Dump(); //打印壁纸
  20.         }
  21.         catch (Exception ex)
  22.         {
  23.                 Console.WriteLine(ex.Message);
  24.         }
  25. }
复制代码
效果预览


API封装

点击查看代码
  1. using System;
  2. using System.Diagnostics;
  3. using System.Drawing.Imaging;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Text.Json;
  7. using System.Threading.Tasks;
  8.    /// <summary>
  9.    /// 加载Bing壁纸,单例,使用CreateInstance方法创建类的实例
  10.    /// </summary>
  11.    public sealed class BingWallpaperAPI
  12.    {
  13.        private static BingWallpaperAPI _instance = null;
  14.        private static readonly object _padlock = new Object();
  15.        /// <summary>
  16.        /// 创建类的实例
  17.        /// </summary>
  18.        /// <param name="imgnums">壁纸的张数,可以是1-8之间的数</param>
  19.        /// <returns></returns>
  20.        public static BingWallpaperAPI CreateInstance(byte imgnums = 3)
  21.        {
  22.            if (_instance is null)
  23.            {
  24.                lock (_padlock)
  25.                {
  26.                    if (_instance is null) _instance = new BingWallpaperAPI(imgnums);
  27.                }
  28.            }
  29.            return _instance;
  30.        }
  31.        private BingWallpaperAPI(byte imgnums)
  32.        {
  33.            if (imgnums > 8 || imgnums <= 0)
  34.            {
  35.                _imgnums = 3;
  36.                Debug.WriteLine($"仅支持1-8张图片,你输入的{imgnums}被重置为3");
  37.            }
  38.            else { _imgnums = imgnums; }
  39.            GetWallpaperLink();
  40.        }
  41.        /// <summary>内置索引</summary>
  42.        private int _index = -1;
  43.        /// <summary>
  44.        /// 加载Bing壁纸的数量,默认为3
  45.        /// </summary>
  46.        private static byte _imgnums;
  47.        private BingApiModel _bingApiModel;
  48.        /// <summary>
  49.        /// 加载壁纸的JSON格式文件,文件中包含了壁纸的下载地址等关键信息
  50.        /// </summary>
  51.        /// <exception cref="Exception"></exception>
  52.        private void GetWallpaperLink()
  53.        {
  54.            HttpClient client = new HttpClient();
  55.            for (int i = 0; i < 3; i++) //这个步骤会尝试3次
  56.            {
  57.                try
  58.                {
  59.                    var res = client.GetAsync($"https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n={_imgnums}&mkt=zh-CN").Result;
  60.                    //参数n:1-8 返回请求数量,目前最多一次获取8张
  61.                    //参数format:js/xml
  62.                    //参数idx:请求图片截止天数 0 今天;1 截止至昨天,类推(目前最多获取到7天前的图片)
  63.                    //参数mkt:地区
  64.                    var json = res.Content.ReadAsStringAsync().Result;
  65.                    BingApiModel bingApiModel = new BingApiModel();
  66.                    _bingApiModel = JsonSerializer.Deserialize<BingApiModel>(json);
  67.                    ImageCount = _bingApiModel.images.Count();
  68.                    if (ImageCount == _imgnums)
  69.                    {
  70.                        break;  //加载成功时直接终止循环
  71.                    }
  72.                }
  73.                catch (Exception ex)
  74.                {
  75.                    if (i == 2) { throw ex; } else Console.WriteLine(ex.Message);
  76.                }
  77.            }
  78.        }
  79.        /// <summary>
  80.        /// 根据JSON数据下载壁纸
  81.        /// </summary>
  82.        /// <param name="index">_bingApiModel索引</param>
  83.        /// <returns></returns>
  84.        /// <exception cref="Exception"></exception>
  85.        private async Task<BingWallpaper> GetWallpaper(int index)
  86.        {
  87.            try
  88.            {
  89.                using (HttpClient client = new HttpClient())
  90.                {
  91.                    var element = _bingApiModel.images[index];
  92.                    var res = await client.GetAsync("https://cn.bing.com" + element.url);
  93.                    //这个URL中的第一个1920x1080改成UHD是4k
  94.                    var imgStream = await res.Content.ReadAsStreamAsync();
  95.                    return (new BingWallpaper()
  96.                    {
  97.                        Wallpaper = System.Drawing.Image.FromStream(imgStream),
  98.                        Title = element.title,
  99.                        Copyright = element.copyright,
  100.                        CopyrightLink = element.copyrightlink,
  101.                        EndDate = element.enddate,
  102.                    });
  103.                }
  104.            }
  105.            catch (Exception ex)
  106.            {
  107.                throw ex;
  108.            }
  109.        }
  110.        /// <summary>
  111.        /// 加载JSON数据包含的URL数量
  112.        /// </summary>
  113.        public int ImageCount { get;private set; }
  114.        /// <summary>
  115.        /// 下一张壁纸
  116.        /// </summary>
  117.        /// <returns></returns>        
  118.        /// <exception cref="Exception"></exception>
  119.        public async Task<BingWallpaper> Next()
  120.        {
  121.            if (ImageCount == 0)
  122.            {
  123.                return null;
  124.            }
  125.            _index++;
  126.            if (_index >= ImageCount)   //重置索引
  127.            {
  128.                _index = 0;
  129.            }
  130.            return await GetWallpaper(_index);
  131.        }
  132.        /// <summary>
  133.        /// 上一张壁纸
  134.        /// </summary>
  135.        /// <returns></returns>
  136.        /// <exception cref="Exception"></exception>
  137.        public async Task<BingWallpaper> Previous()
  138.        {
  139.            if (ImageCount == 0)
  140.            {
  141.                return null;
  142.            }
  143.            _index--;
  144.            if (_index < 0)
  145.            {
  146.                _index = ImageCount - 1;    //重置索引
  147.            }
  148.            return await GetWallpaper(_index);
  149.        }
  150.        /// <summary>
  151.        /// 保存当前的壁纸到本地
  152.        /// </summary>
  153.        /// <param name="path">保存的路径、含文件名(如c:\1.jpg),格式为JPEG</param>
  154.        /// <returns>保存是否成功</returns>
  155.        /// <exception cref="Exception"></exception>
  156.        public async Task<bool> SaveCurrentWallpaper(string path)
  157.        {
  158.            try
  159.            {
  160.                var task = await Current();
  161.                task.Wallpaper.Save(path, ImageFormat.Jpeg);
  162.                return true;
  163.            }
  164.            catch (Exception ex)
  165.            {
  166.                throw ex;
  167.            }
  168.        }
  169.        /// <summary>
  170.        /// 当前壁纸
  171.        /// </summary>
  172.        /// <returns></returns>
  173.        /// <exception cref="Exception"></exception>
  174.        public async Task<BingWallpaper> Current()
  175.        {
  176.            if (ImageCount == 0)
  177.            {
  178.                return null;
  179.            }
  180.            if (_index == -1)
  181.            {
  182.                _index = 0;
  183.            }
  184.            return await GetWallpaper(_index);
  185.        }
  186.    }
  187.    /// <summary>
  188.    /// 用来保存壁纸信息的类模型
  189.    /// </summary>
  190.    public class BingWallpaper
  191.    {
  192.        /// <summary>壁纸</summary>
  193.        public System.Drawing.Image Wallpaper { get; set; }
  194.        /// <summary>标题</summary>
  195.        public string Title { get; set; }
  196.        /// <summary>版权</summary>
  197.        public string Copyright { get; set; }
  198.        /// <summary>版权链接</summary>
  199.        public string CopyrightLink { get; set; }
  200.        /// <summary>
  201.        /// 壁纸所属日期
  202.        /// </summary>
  203.        public string EndDate { get; set; }
  204.    }
  205.    /// <summary>
  206.    /// 用来解析JSON数据的类模型
  207.    /// </summary>
  208.    public class BingApiModel
  209.    {
  210.        /// <summary>
  211.        /// 返回图片集合
  212.        /// </summary>
  213.        public Image[] images { get; set; }
  214.    }
  215.    public class Image
  216.    {
  217.        /// <summary>
  218.        /// 每日壁纸的日期
  219.        /// </summary>
  220.        public string enddate { get; set; }
  221.        /// <summary>
  222.        /// 壁纸的地址
  223.        /// </summary>
  224.        public string url { get; set; }
  225.        /// <summary>壁纸的简述、拍摄地址(摄影人)</summary>
  226.        public string copyright { get; set; }
  227.        /// <summary>壁纸相关搜索链接</summary>
  228.        public string copyrightlink { get; set; }
  229.        /// <summary>壁纸的标题</summary>
  230.        public string title { get; set; }
  231.    }
复制代码
原创声明

作者:落水的月亮
出处:博客园
转载:可以转载,转载必须注明出处。必须在文章中给出原文连接。
必应主页

来源:https://www.cnblogs.com/lsdyl/p/18401036
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具